Skip to main content

mtop/
app.rs

1use std::cmp::Ordering;
2use std::collections::{HashMap, VecDeque};
3use std::time::Duration;
4
5use ratatui::DefaultTerminal;
6use ratatui::crossterm::event::{
7    self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton, MouseEvent,
8    MouseEventKind,
9};
10use ratatui::layout::Rect;
11use ratatui::widgets::TableState;
12
13use crate::apps::AppGroup;
14use crate::cgroup::CgroupMem;
15use crate::i18n::{HelpPage, Lang};
16use crate::model::{Focus, ProcRow, Snapshot, SortKey};
17use crate::procfs::{Vma, VmaGroup};
18use crate::theme::{ColorSupport, Theme};
19use crate::ui;
20
21pub const HISTORY: usize = 120;
22
23#[derive(Clone, Copy, PartialEq, Eq, Debug)]
24pub enum View {
25    Procs,
26    Cgroups,
27    Apps,
28}
29
30/// One sample of an app's three metrics, so switching the map metric does not
31/// mix series (a PSS history is useless when the view shows RSS).
32#[derive(Clone, Copy, Default)]
33pub struct AppSample {
34    pub pss_kb: u64,
35    pub uss_kb: u64,
36    pub rss_kb: u64,
37}
38
39#[derive(Clone, Copy, PartialEq, Eq, Debug)]
40pub enum AppMetric {
41    Pss,
42    Uss,
43    Rss,
44}
45
46impl AppMetric {
47    pub fn label(self) -> &'static str {
48        match self {
49            AppMetric::Pss => "PSS",
50            AppMetric::Uss => "USS",
51            AppMetric::Rss => "RSS",
52        }
53    }
54
55    pub fn value(self, g: &AppGroup) -> u64 {
56        match self {
57            AppMetric::Pss => g.pss_kb,
58            AppMetric::Uss => g.uss_kb,
59            AppMetric::Rss => g.rss_kb,
60        }
61    }
62
63    fn next(self) -> Self {
64        match self {
65            AppMetric::Pss => AppMetric::Uss,
66            AppMetric::Uss => AppMetric::Rss,
67            AppMetric::Rss => AppMetric::Pss,
68        }
69    }
70}
71
72#[derive(Clone, Copy, PartialEq, Eq, Debug)]
73pub enum CgroupSort {
74    Current,
75    Anon,
76    File,
77    Slab,
78}
79
80impl CgroupSort {
81    const ALL: [CgroupSort; 4] = [
82        CgroupSort::Current,
83        CgroupSort::Anon,
84        CgroupSort::File,
85        CgroupSort::Slab,
86    ];
87
88    pub fn label(self) -> &'static str {
89        match self {
90            CgroupSort::Current => "CUR",
91            CgroupSort::Anon => "ANON",
92            CgroupSort::File => "FILE",
93            CgroupSort::Slab => "SLAB",
94        }
95    }
96
97    fn next(self) -> Self {
98        let i = Self::ALL.iter().position(|k| *k == self).unwrap_or(0);
99        Self::ALL[(i + 1) % Self::ALL.len()]
100    }
101
102    fn key(self, c: &CgroupMem) -> u64 {
103        match self {
104            CgroupSort::Current => c.current_kb,
105            CgroupSort::Anon => c.anon_kb,
106            CgroupSort::File => c.file_kb,
107            CgroupSort::Slab => c.slab_kb,
108        }
109    }
110}
111
112/// A row in the detail view: either an aggregated mapping or one VMA inside it.
113pub enum DetailRow<'a> {
114    Group(&'a VmaGroup),
115    Vma(&'a VmaGroup, &'a Vma),
116}
117
118/// An open help overlay: which page's documentation is shown and how far it
119/// has been scrolled.
120pub struct HelpState {
121    pub page: HelpPage,
122    pub scroll: u16,
123}
124
125/// A clickable footer action.
126#[derive(Clone, Copy, Debug, PartialEq, Eq)]
127pub enum FooterAction {
128    View,
129    Sort,
130    Reverse,
131    Filter,
132    Enter,
133    Back,
134    Theme,
135    Lang,
136    Help,
137    Quit,
138}
139
140/// What a mouse hit region refers to.
141#[derive(Clone, Copy, Debug)]
142pub enum MouseTarget {
143    Row(usize),
144    Tile(usize),
145    Button(FooterAction),
146    HelpArea,
147}
148
149#[derive(Clone, Copy, Debug)]
150pub struct Hit {
151    pub rect: Rect,
152    pub target: MouseTarget,
153}
154
155pub struct App {
156    pub view: View,
157    /// Active built-in theme; `t` cycles it.
158    pub theme: Theme,
159    /// Terminal colour depth the active palette was rendered for.
160    pub support: ColorSupport,
161    /// UI language; `l` toggles it.
162    pub lang: Lang,
163    /// Open help overlay, if any.
164    pub help: Option<HelpState>,
165    /// Click targets recorded by the last draw.
166    pub hits: Vec<Hit>,
167    pub sort: SortKey,
168    pub cgroup_sort: CgroupSort,
169    pub cgroup_sel: usize,
170    /// App groups for the treemap, recomputed per snapshot (collapsed to the
171    /// top few percent so the map does not dissolve into slivers).
172    pub app_groups: Vec<AppGroup>,
173    /// Metric history per app name (only the collapsed groups are tracked:
174    /// ~20-40 entries, not all 330).
175    pub app_history: HashMap<String, VecDeque<AppSample>>,
176    pub app_sel: usize,
177    pub app_metric: AppMetric,
178    pub app_state: TableState,
179    /// Drill target coming from the apps view: only these pids are shown in
180    /// the process table.
181    pub pid_filter: Option<std::collections::HashSet<u32>>,
182    pub pid_filter_name: Option<String>,
183    /// cgroup path whose processes are being listed (drill-down).
184    pub drill: Option<String>,
185    pub drill_sel: usize,
186    pub desc: bool,
187    pub filter: String,
188    /// Mapping-name filter for the VMA detail view (independent of `filter`).
189    pub detail_filter: String,
190    /// Group labels whose VMAs are expanded.
191    pub expanded: std::collections::HashSet<String>,
192    pub editing: bool,
193    /// Whether the in-progress edit targets the detail filter.
194    pub editing_detail: bool,
195    pub edit_buf: String,
196    pub sel: usize,
197    pub detail: bool,
198    pub detail_sel: usize,
199    pub snap: Option<Snapshot>,
200    pub table_state: TableState,
201    pub cgroup_state: TableState,
202    pub drill_state: TableState,
203    pub detail_state: TableState,
204    pub history: HashMap<u32, VecDeque<u64>>,
205    /// PSI `some avg10` over time per cgroup, stored as percent*10 for the
206    /// sparkline (u64) with a fixed 0-1000 scale.
207    pub cgroup_history: HashMap<String, VecDeque<u64>>,
208    /// OOM kills per scan per cgroup (5 s cadence, 120 samples = 10 min).
209    pub oom_history: HashMap<String, VecDeque<u64>>,
210    last_scan_seq: u64,
211    last_sent: Option<(Option<u32>, bool)>,
212    started: bool,
213    pending_focus: Option<u32>,
214    detail_pid: Option<u32>,
215}
216
217impl App {
218    pub fn new(start_pid: Option<u32>) -> Self {
219        let mut app = App {
220            view: View::Procs,
221            theme: Theme::DEFAULT,
222            support: ColorSupport::TrueColor,
223            lang: Lang::En,
224            help: None,
225            hits: Vec::new(),
226            sort: SortKey::Rss,
227            cgroup_sort: CgroupSort::Current,
228            cgroup_sel: 0,
229            app_groups: Vec::new(),
230            app_history: HashMap::new(),
231            app_sel: 0,
232            app_metric: AppMetric::Pss,
233            app_state: TableState::default(),
234            pid_filter: None,
235            pid_filter_name: None,
236            drill: None,
237            drill_sel: 0,
238            desc: true,
239            filter: String::new(),
240            detail_filter: String::new(),
241            expanded: std::collections::HashSet::new(),
242            editing: false,
243            editing_detail: false,
244            edit_buf: String::new(),
245            sel: 0,
246            detail: false,
247            detail_sel: 0,
248            snap: None,
249            table_state: TableState::default(),
250            cgroup_state: TableState::default(),
251            drill_state: TableState::default(),
252            detail_state: TableState::default(),
253            history: HashMap::new(),
254            cgroup_history: HashMap::new(),
255            oom_history: HashMap::new(),
256            last_scan_seq: 0,
257            last_sent: None,
258            started: false,
259            pending_focus: None,
260            detail_pid: None,
261        };
262        if let Some(pid) = start_pid {
263            app.pending_focus = Some(pid);
264        }
265        app
266    }
267
268    fn ratio(&self, r: &ProcRow) -> f64 {
269        let pss = self
270            .snap
271            .as_ref()
272            .and_then(|s| s.pss.get(&r.pid))
273            .map(|p| p.rollup.pss_kb)
274            .unwrap_or(0);
275        if r.rss_kb == 0 {
276            0.0
277        } else {
278            pss as f64 / r.rss_kb as f64
279        }
280    }
281
282    pub fn visible(&self) -> Vec<&ProcRow> {
283        let Some(snap) = &self.snap else {
284            return Vec::new();
285        };
286        let needle = self.filter.to_lowercase();
287        let mut rows: Vec<&ProcRow> = snap
288            .rows
289            .iter()
290            .filter(|r| {
291                self.pid_filter
292                    .as_ref()
293                    .is_none_or(|set| set.contains(&r.pid))
294            })
295            .filter(|r| {
296                needle.is_empty()
297                    || r.comm.to_lowercase().contains(&needle)
298                    || r.pid.to_string().starts_with(&needle)
299            })
300            .collect();
301        let pss = |pid: u32| snap.pss.get(&pid).map(|p| p.rollup.pss_kb).unwrap_or(0);
302        let uss = |pid: u32| snap.pss.get(&pid).map(|p| p.rollup.uss_kb).unwrap_or(0);
303        let sort = self.sort;
304        let desc = self.desc;
305        rows.sort_by(|a, b| {
306            let ord = match sort {
307                SortKey::Rss => a.rss_kb.cmp(&b.rss_kb),
308                SortKey::Pss => pss(a.pid).cmp(&pss(b.pid)),
309                SortKey::Uss => uss(a.pid).cmp(&uss(b.pid)),
310                SortKey::Delta => a.delta_kb.cmp(&b.delta_kb),
311                SortKey::Ratio => self
312                    .ratio(a)
313                    .partial_cmp(&self.ratio(b))
314                    .unwrap_or(Ordering::Equal),
315                SortKey::Pid => a.pid.cmp(&b.pid),
316                SortKey::Comm => a.comm.to_lowercase().cmp(&b.comm.to_lowercase()),
317            };
318            let ord = if desc { ord.reverse() } else { ord };
319            ord.then_with(|| a.pid.cmp(&b.pid))
320        });
321        rows
322    }
323
324    pub fn visible_cgroups(&self) -> Vec<&CgroupMem> {
325        let Some(snap) = &self.snap else {
326            return Vec::new();
327        };
328        let needle = self.filter.to_lowercase();
329        let mut rows: Vec<&CgroupMem> = snap
330            .cgroups
331            .iter()
332            .filter(|c| needle.is_empty() || c.path.to_lowercase().contains(&needle))
333            .collect();
334        rows.sort_by_key(|c| self.cgroup_sort.key(c));
335        if self.desc {
336            rows.reverse();
337        }
338        rows
339    }
340
341    /// Processes whose cgroup is `drill` or a descendant of it. The cgroup
342    /// numbers are hierarchical, so the subtree is what you want to see.
343    pub fn cgroup_members(&self) -> Vec<&ProcRow> {
344        let (Some(path), Some(snap)) = (&self.drill, &self.snap) else {
345            return Vec::new();
346        };
347        let prefix = if path == "/" {
348            "/".to_string()
349        } else {
350            format!("{path}/")
351        };
352        let mut rows: Vec<&ProcRow> = snap
353            .rows
354            .iter()
355            .filter(|r| {
356                snap.pid_cgroup
357                    .get(&r.pid)
358                    .is_some_and(|c| c == path || c.starts_with(&prefix))
359            })
360            .collect();
361        rows.sort_by_key(|r| std::cmp::Reverse(r.rss_kb));
362        rows
363    }
364
365    /// Series for the selected metric of `name`, for the header sparkline.
366    pub fn app_series(&self, name: &str, metric: AppMetric) -> Vec<u64> {
367        self.app_history
368            .get(name)
369            .map(|h| {
370                h.iter()
371                    .map(|s| match metric {
372                        AppMetric::Pss => s.pss_kb,
373                        AppMetric::Uss => s.uss_kb,
374                        AppMetric::Rss => s.rss_kb,
375                    })
376                    .collect()
377            })
378            .unwrap_or_default()
379    }
380
381    pub fn visible_apps(&self) -> Vec<&AppGroup> {
382        let needle = self.filter.to_lowercase();
383        self.app_groups
384            .iter()
385            .filter(|g| needle.is_empty() || g.name.to_lowercase().contains(&needle))
386            .collect()
387    }
388
389    pub fn selected_app(&self) -> Option<&AppGroup> {
390        self.visible_apps().get(self.app_sel).copied()
391    }
392
393    pub fn selected_pid(&self) -> Option<u32> {
394        // While the detail view is open the focused pid comes from the loaded
395        // detail, but it must fall back to the table selection: the Enter
396        // keypress happens one snapshot before detail exists, and returning
397        // None there drops the focus request entirely.
398        if self.detail
399            && let Some(pid) = self
400                .snap
401                .as_ref()
402                .and_then(|s| s.detail.as_ref())
403                .map(|d| d.pid)
404        {
405            return Some(pid);
406        }
407        self.visible().get(self.sel).map(|r| r.pid)
408    }
409
410    /// The (pid, want_detail) pair the sampler should be working on.
411    pub fn focus_target(&self) -> (Option<u32>, bool) {
412        if let Some(pid) = self.pending_focus {
413            return (Some(pid), self.detail);
414        }
415        (self.selected_pid(), self.detail)
416    }
417
418    pub fn take_focus_update(&mut self) -> Option<Focus> {
419        let target = self.focus_target();
420        if self.last_sent == Some(target) {
421            return None;
422        }
423        self.last_sent = Some(target);
424        Some(Focus::Set {
425            pid: target.0,
426            want_detail: target.1,
427        })
428    }
429
430    pub fn on_snapshot(&mut self, snap: Snapshot) {
431        let mut seen: Vec<u32> = Vec::with_capacity(snap.rows.len());
432        for row in &snap.rows {
433            seen.push(row.pid);
434            let h = self.history.entry(row.pid).or_default();
435            h.push_back(row.rss_kb);
436            while h.len() > HISTORY {
437                h.pop_front();
438            }
439        }
440        self.history.retain(|pid, _| seen.contains(pid));
441        self.app_groups = crate::apps::collapse(
442            crate::apps::group(&snap.rows, &snap.pss, &snap.pid_cgroup, &snap.pid_exe),
443            0.005,
444        );
445        let mut app_seen: std::collections::HashSet<&str> =
446            std::collections::HashSet::with_capacity(self.app_groups.len());
447        for g in &self.app_groups {
448            app_seen.insert(g.name.as_str());
449            let h = self.app_history.entry(g.name.clone()).or_default();
450            h.push_back(AppSample {
451                pss_kb: g.pss_kb,
452                uss_kb: g.uss_kb,
453                rss_kb: g.rss_kb,
454            });
455            while h.len() > HISTORY {
456                h.pop_front();
457            }
458        }
459        self.app_history
460            .retain(|name, _| app_seen.contains(name.as_str()));
461
462        // The cgroup list only changes on the 5 s scan; sampling it every tick
463        // would record the same value five times and shrink the window.
464        if snap.scan_seq != self.last_scan_seq && !snap.cgroups.is_empty() {
465            self.last_scan_seq = snap.scan_seq;
466            let mut cg_seen: std::collections::HashSet<&str> =
467                std::collections::HashSet::with_capacity(snap.cgroups.len());
468            for cg in &snap.cgroups {
469                cg_seen.insert(cg.path.as_str());
470                let h = self.cgroup_history.entry(cg.path.clone()).or_default();
471                h.push_back((cg.psi_some10.max(0.0) * 10.0).round() as u64);
472                while h.len() > HISTORY {
473                    h.pop_front();
474                }
475                let o = self.oom_history.entry(cg.path.clone()).or_default();
476                o.push_back(cg.oom_recent);
477                while o.len() > HISTORY {
478                    o.pop_front();
479                }
480            }
481            self.cgroup_history
482                .retain(|path, _| cg_seen.contains(path.as_str()));
483            self.oom_history
484                .retain(|path, _| cg_seen.contains(path.as_str()));
485        }
486        self.snap = Some(snap);
487        // A different process means a different mapping tree: reset expansion.
488        let pid = self
489            .snap
490            .as_ref()
491            .and_then(|s| s.detail.as_ref())
492            .map(|d| d.pid);
493        if pid != self.detail_pid {
494            self.detail_pid = pid;
495            self.expanded.clear();
496            self.detail_sel = 0;
497        }
498        if let Some(pid) = self.pending_focus
499            && let Some(i) = self.visible().iter().position(|r| r.pid == pid)
500        {
501            self.sel = i;
502            self.pending_focus = None;
503        }
504        self.clamp();
505    }
506
507    /// Flattened detail rows: every matching group, followed by its VMAs when
508    /// expanded. Selection indexes into this vector.
509    pub fn detail_rows(&self) -> Vec<DetailRow<'_>> {
510        let needle = self.detail_filter.to_lowercase();
511        let Some(d) = self.snap.as_ref().and_then(|s| s.detail.as_ref()) else {
512            return Vec::new();
513        };
514        let mut out = Vec::with_capacity(d.report.groups.len());
515        for g in &d.report.groups {
516            if !needle.is_empty() && !g.label.to_lowercase().contains(&needle) {
517                continue;
518            }
519            out.push(DetailRow::Group(g));
520            if self.expanded.contains(&g.label) {
521                out.extend(g.vmas.iter().map(|v| DetailRow::Vma(g, v)));
522            }
523        }
524        out
525    }
526
527    pub fn detail_len(&self) -> usize {
528        self.detail_rows().len()
529    }
530
531    fn toggle_expand(&mut self) {
532        let label = match self.detail_rows().get(self.detail_sel) {
533            Some(DetailRow::Group(g)) => g.label.clone(),
534            _ => return,
535        };
536        if !self.expanded.remove(&label) {
537            self.expanded.insert(label);
538        }
539    }
540
541    fn clamp(&mut self) {
542        let n_proc = self.visible().len();
543        self.sel = self.sel.min(n_proc.saturating_sub(1));
544        let n_cg = self.visible_cgroups().len();
545        self.cgroup_sel = self.cgroup_sel.min(n_cg.saturating_sub(1));
546        let n_members = self.cgroup_members().len();
547        self.drill_sel = self.drill_sel.min(n_members.saturating_sub(1));
548        let n_apps = self.visible_apps().len();
549        self.app_sel = self.app_sel.min(n_apps.saturating_sub(1));
550        self.detail_sel = self.detail_sel.min(self.detail_len().saturating_sub(1));
551        self.table_state.select(Some(self.sel));
552        self.cgroup_state.select(Some(self.cgroup_sel));
553        self.app_state.select(Some(self.app_sel));
554        self.drill_state.select(Some(self.drill_sel));
555        self.detail_state.select(Some(self.detail_sel));
556    }
557
558    fn help_page(&self) -> HelpPage {
559        match self.view {
560            View::Procs if self.detail => HelpPage::Detail,
561            View::Procs => HelpPage::Procs,
562            View::Cgroups if self.drill.is_some() => HelpPage::CgroupDrill,
563            View::Cgroups => HelpPage::Cgroups,
564            View::Apps => HelpPage::Apps,
565        }
566    }
567
568    fn help_scroll(&mut self, delta: i32) {
569        if let Some(help) = &mut self.help {
570            help.scroll = if delta >= 0 {
571                help.scroll.saturating_add(delta as u16)
572            } else {
573                help.scroll.saturating_sub((-delta) as u16)
574            };
575        }
576    }
577
578    fn cycle_view(&mut self) {
579        self.view = match self.view {
580            View::Procs => View::Cgroups,
581            View::Cgroups => View::Apps,
582            View::Apps => View::Procs,
583        };
584        self.detail = false;
585        self.drill = None;
586        self.editing = false;
587    }
588
589    fn cycle_sort(&mut self) {
590        if self.view == View::Apps {
591            self.app_metric = self.app_metric.next();
592            self.app_sel = 0;
593        } else if self.view == View::Cgroups {
594            self.cgroup_sort = self.cgroup_sort.next();
595            self.cgroup_sel = 0;
596        } else {
597            self.sort = self.sort.next();
598            self.sel = 0;
599        }
600    }
601
602    fn start_filter(&mut self) {
603        self.editing = true;
604        self.editing_detail = self.detail;
605        self.edit_buf = if self.detail {
606            self.detail_filter.clone()
607        } else {
608            self.filter.clone()
609        };
610    }
611
612    fn toggle_reverse(&mut self) {
613        self.desc = !self.desc;
614    }
615
616    fn toggle_theme(&mut self) {
617        self.theme = self.theme.next().rendered(self.support);
618    }
619
620    fn toggle_lang(&mut self) {
621        self.lang = self.lang.toggle();
622    }
623
624    fn open_help(&mut self) {
625        self.help = Some(HelpState {
626            page: self.help_page(),
627            scroll: 0,
628        });
629    }
630
631    fn enter_action(&mut self) {
632        if self.view == View::Apps {
633            let target = self
634                .selected_app()
635                .filter(|g| !g.synthetic)
636                .map(|g| (g.name.clone(), g.pids.clone()));
637            if let Some((name, pids)) = target {
638                self.pid_filter = Some(pids.into_iter().collect());
639                self.pid_filter_name = Some(name);
640                self.view = View::Procs;
641                self.sel = 0;
642                self.detail = false;
643            }
644        } else if self.view == View::Cgroups {
645            if self.drill.is_none()
646                && let Some(path) = self
647                    .visible_cgroups()
648                    .get(self.cgroup_sel)
649                    .map(|c| c.path.clone())
650            {
651                self.drill = Some(path);
652                self.drill_sel = 0;
653            }
654        } else if self.detail {
655            self.toggle_expand();
656        } else if self.selected_pid().is_some() {
657            self.detail = true;
658            self.detail_sel = 0;
659        }
660    }
661
662    fn escape_action(&mut self) {
663        if self.pid_filter.is_some() {
664            self.pid_filter = None;
665            self.pid_filter_name = None;
666            self.sel = 0;
667        } else if self.view == View::Cgroups && self.drill.is_some() {
668            self.drill = None;
669            self.drill_sel = 0;
670        } else if self.detail && !self.detail_filter.is_empty() {
671            self.detail_filter.clear();
672            self.detail_sel = 0;
673        } else if self.detail {
674            self.detail = false;
675            self.detail_sel = 0;
676        } else if !self.filter.is_empty() {
677            self.filter.clear();
678            self.sel = 0;
679        }
680    }
681
682    fn click_row(&mut self, index: usize) {
683        match self.view {
684            View::Procs if self.detail => {
685                if self.detail_sel == index {
686                    self.enter_action();
687                } else {
688                    self.detail_sel = index;
689                }
690            }
691            View::Procs => {
692                if self.sel == index {
693                    self.enter_action();
694                } else {
695                    self.sel = index;
696                }
697            }
698            View::Cgroups if self.drill.is_some() => {
699                self.drill_sel = index;
700            }
701            View::Cgroups => {
702                if self.cgroup_sel == index {
703                    self.enter_action();
704                } else {
705                    self.cgroup_sel = index;
706                }
707            }
708            View::Apps => {
709                if self.app_sel == index {
710                    self.enter_action();
711                } else {
712                    self.app_sel = index;
713                }
714            }
715        }
716    }
717
718    fn click_tile(&mut self, index: usize) {
719        if self.app_sel == index {
720            self.enter_action();
721        } else {
722            self.app_sel = index;
723        }
724    }
725
726    fn footer_action(&mut self, action: FooterAction) -> bool {
727        match action {
728            FooterAction::Quit => return true,
729            FooterAction::Help => self.open_help(),
730            FooterAction::Lang => self.toggle_lang(),
731            FooterAction::Theme => self.toggle_theme(),
732            FooterAction::View => self.cycle_view(),
733            FooterAction::Sort => self.cycle_sort(),
734            FooterAction::Reverse => self.toggle_reverse(),
735            FooterAction::Filter => self.start_filter(),
736            FooterAction::Enter => self.enter_action(),
737            FooterAction::Back => self.escape_action(),
738        }
739        self.clamp();
740        false
741    }
742
743    pub fn on_mouse(&mut self, mouse: MouseEvent) -> bool {
744        if self.editing {
745            return false;
746        }
747        if self.help.is_some() {
748            match mouse.kind {
749                MouseEventKind::ScrollDown => self.help_scroll(3),
750                MouseEventKind::ScrollUp => self.help_scroll(-3),
751                MouseEventKind::Down(MouseButton::Left) => {
752                    let inside = self.hits.iter().any(|hit| {
753                        matches!(hit.target, MouseTarget::HelpArea)
754                            && mouse.column >= hit.rect.x
755                            && mouse.column < hit.rect.x.saturating_add(hit.rect.width)
756                            && mouse.row >= hit.rect.y
757                            && mouse.row < hit.rect.y.saturating_add(hit.rect.height)
758                    });
759                    if !inside {
760                        self.help = None;
761                    }
762                }
763                _ => {}
764            }
765            return false;
766        }
767        match mouse.kind {
768            MouseEventKind::ScrollDown => self.move_sel(3),
769            MouseEventKind::ScrollUp => self.move_sel(-3),
770            MouseEventKind::Down(MouseButton::Left) => {
771                let target = self
772                    .hits
773                    .iter()
774                    .rev()
775                    .find(|hit| {
776                        let r = hit.rect;
777                        mouse.column >= r.x
778                            && mouse.column < r.x.saturating_add(r.width)
779                            && mouse.row >= r.y
780                            && mouse.row < r.y.saturating_add(r.height)
781                    })
782                    .map(|hit| hit.target);
783                match target {
784                    Some(MouseTarget::Row(index)) => self.click_row(index),
785                    Some(MouseTarget::Tile(index)) => self.click_tile(index),
786                    Some(MouseTarget::Button(action)) => return self.footer_action(action),
787                    Some(MouseTarget::HelpArea) | None => return false,
788                }
789            }
790            _ => return false,
791        }
792        self.clamp();
793        false
794    }
795
796    pub fn handle_event(&mut self, event: Event) -> bool {
797        match event {
798            Event::Key(key) => self.on_key(key),
799            Event::Mouse(mouse) => self.on_mouse(mouse),
800            _ => false,
801        }
802    }
803
804    /// Returns true when the app should exit.
805    pub fn on_key(&mut self, key: KeyEvent) -> bool {
806        if key.kind != KeyEventKind::Press {
807            return false;
808        }
809        if self.help.is_some() {
810            match key.code {
811                KeyCode::Char('q') => return true,
812                KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => return true,
813                KeyCode::Esc | KeyCode::Char('?') => self.help = None,
814                KeyCode::Char('j') | KeyCode::Down => self.help_scroll(1),
815                KeyCode::Char('k') | KeyCode::Up => self.help_scroll(-1),
816                KeyCode::PageDown => self.help_scroll(10),
817                KeyCode::PageUp => self.help_scroll(-10),
818                KeyCode::Char('g') | KeyCode::Home => {
819                    if let Some(help) = &mut self.help {
820                        help.scroll = 0;
821                    }
822                }
823                KeyCode::Char('G') | KeyCode::End => {
824                    if let Some(help) = &mut self.help {
825                        help.scroll = u16::MAX;
826                    }
827                }
828                KeyCode::Char('l') => self.lang = self.lang.toggle(),
829                _ => {}
830            }
831            return false;
832        }
833        if self.editing {
834            return self.on_edit_key(key);
835        }
836        match key.code {
837            KeyCode::Char('q') => return true,
838            KeyCode::Char('?') => self.open_help(),
839            KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => return true,
840            KeyCode::Tab => self.cycle_view(),
841            KeyCode::Char('j') | KeyCode::Down => self.move_sel(1),
842            KeyCode::Char('k') | KeyCode::Up => self.move_sel(-1),
843            KeyCode::PageDown => self.move_sel(10),
844            KeyCode::PageUp => self.move_sel(-10),
845            KeyCode::Char('g') | KeyCode::Home => {
846                self.sel = 0;
847                self.detail_sel = 0;
848                self.cgroup_sel = 0;
849                self.drill_sel = 0;
850                self.app_sel = 0;
851            }
852            KeyCode::Char('G') | KeyCode::End => {
853                self.sel = usize::MAX / 2;
854                self.cgroup_sel = usize::MAX / 2;
855                self.drill_sel = usize::MAX / 2;
856                self.app_sel = usize::MAX / 2;
857            }
858            KeyCode::Char('s') => self.cycle_sort(),
859            KeyCode::Char('r') => self.toggle_reverse(),
860            KeyCode::Char('t') => self.toggle_theme(),
861            KeyCode::Char('l') => self.toggle_lang(),
862            KeyCode::Char('f') => self.start_filter(),
863            KeyCode::Enter | KeyCode::Char(' ') => self.enter_action(),
864            KeyCode::Char('z') if self.detail => self.expanded.clear(),
865            KeyCode::Char('Z') if self.detail => {
866                if let Some(d) = self.snap.as_ref().and_then(|s| s.detail.as_ref()) {
867                    self.expanded
868                        .extend(d.report.groups.iter().map(|g| g.label.clone()));
869                }
870            }
871            KeyCode::Esc => self.escape_action(),
872            _ => {}
873        }
874        self.clamp();
875        false
876    }
877
878    fn on_edit_key(&mut self, key: KeyEvent) -> bool {
879        match key.code {
880            KeyCode::Enter => {
881                if self.editing_detail {
882                    self.detail_filter = self.edit_buf.clone();
883                    self.detail_sel = 0;
884                } else {
885                    self.filter = self.edit_buf.clone();
886                    self.sel = 0;
887                }
888                self.editing = false;
889                self.editing_detail = false;
890            }
891            KeyCode::Esc => {
892                self.editing = false;
893                self.editing_detail = false;
894                self.edit_buf.clear();
895            }
896            KeyCode::Backspace => {
897                self.edit_buf.pop();
898            }
899            KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => return true,
900            KeyCode::Char(c) => self.edit_buf.push(c),
901            _ => {}
902        }
903        self.clamp();
904        false
905    }
906
907    fn move_sel(&mut self, delta: isize) {
908        if self.view == View::Apps {
909            let n = self.visible_apps().len();
910            self.app_sel = step(self.app_sel, delta, n);
911            return;
912        }
913        if self.view == View::Cgroups {
914            if self.drill.is_some() {
915                let n = self.cgroup_members().len();
916                self.drill_sel = step(self.drill_sel, delta, n);
917            } else {
918                let n = self.visible_cgroups().len();
919                self.cgroup_sel = step(self.cgroup_sel, delta, n);
920            }
921            return;
922        }
923        if self.detail {
924            let n = self.detail_len();
925            self.detail_sel = step(self.detail_sel, delta, n);
926            return;
927        }
928        let n = self.visible().len();
929        self.sel = step(self.sel, delta, n);
930    }
931
932    pub fn run(
933        terminal: &mut DefaultTerminal,
934        start_pid: Option<u32>,
935        theme: Theme,
936        support: ColorSupport,
937        lang: Lang,
938        tx: std::sync::mpsc::Sender<Focus>,
939        rx: std::sync::mpsc::Receiver<Snapshot>,
940    ) -> std::io::Result<()> {
941        let mut app = App::new(start_pid);
942        app.support = support;
943        app.theme = theme.rendered(support);
944        app.lang = lang;
945        loop {
946            let mut got = false;
947            while let Ok(snap) = rx.try_recv() {
948                app.on_snapshot(snap);
949                got = true;
950            }
951            if got || app.started {
952                terminal.draw(|f| ui::draw(f, &mut app))?;
953                app.started = true;
954            }
955            if let Some(focus) = app.take_focus_update() {
956                let _ = tx.send(focus);
957            }
958            if event::poll(Duration::from_millis(250))? {
959                if app.handle_event(event::read()?) {
960                    return Ok(());
961                }
962                while event::poll(Duration::ZERO)? {
963                    if app.handle_event(event::read()?) {
964                        return Ok(());
965                    }
966                }
967                if let Some(focus) = app.take_focus_update() {
968                    let _ = tx.send(focus);
969                }
970            }
971        }
972    }
973
974    pub fn sample_age_ms(&self) -> u128 {
975        self.snap
976            .as_ref()
977            .map(|s| s.at.elapsed().as_millis())
978            .unwrap_or(0)
979    }
980}
981
982fn step(cur: usize, delta: isize, n: usize) -> usize {
983    if n == 0 {
984        return 0;
985    }
986    let max = n - 1;
987    if delta >= 0 {
988        (cur + delta as usize).min(max)
989    } else {
990        cur.saturating_sub((-delta) as usize)
991    }
992}