Skip to main content

mtop/
apps.rs

1//! Grouping processes into "apps" and squarified treemap layout.
2//!
3//! The grouping order matters and is documented in REQUIREMENTS: a systemd
4//! `app-*.scope` wins because it encodes the app's own intent (helpers
5//! included), then the executable, then comm. Chrome is the motivating case:
6//! one desktop app, two scopes and 29 processes.
7
8use std::collections::HashMap;
9
10use ratatui::layout::Rect;
11
12use crate::model::{ProcRow, PssInfo};
13
14#[derive(Clone, Debug, Default, PartialEq, Eq)]
15pub struct AppGroup {
16    pub name: String,
17    pub pss_kb: u64,
18    pub uss_kb: u64,
19    pub rss_kb: u64,
20    pub procs: u32,
21    pub pids: Vec<u32>,
22    /// The "others" tile collects the long tail and cannot be drilled into.
23    pub synthetic: bool,
24}
25
26/// systemd escapes '-' as `\x2d` inside unit names.
27pub fn unescape_scope(s: &str) -> String {
28    let mut out = String::with_capacity(s.len());
29    let mut chars = s.chars().peekable();
30    while let Some(c) = chars.next() {
31        if c == '\\' && chars.peek() == Some(&'x') {
32            chars.next();
33            let mut hex = String::with_capacity(2);
34            for _ in 0..2 {
35                if let Some(h) = chars.next() {
36                    hex.push(h);
37                }
38            }
39            match u8::from_str_radix(&hex, 16) {
40                Ok(v) => out.push(v as char),
41                Err(_) => {
42                    out.push('\\');
43                    out.push('x');
44                    out.push_str(&hex);
45                }
46            }
47        } else {
48            out.push(c);
49        }
50    }
51    out
52}
53
54/// `ghostty-surface-transient-600564` -> `ghostty-surface-transient`.
55fn strip_trailing_pid(s: &str) -> &str {
56    match s.rsplit_once('-') {
57        Some((head, tail))
58            if !head.is_empty() && !tail.is_empty() && tail.bytes().all(|b| b.is_ascii_digit()) =>
59        {
60            head
61        }
62        _ => s,
63    }
64}
65
66fn scope_app_name(cgroup_path: &str) -> Option<String> {
67    let last = cgroup_path.rsplit('/').next().unwrap_or("");
68    let body = last.strip_prefix("app-")?.strip_suffix(".scope")?;
69    let name = strip_trailing_pid(&unescape_scope(body)).to_string();
70    (!name.is_empty()).then_some(name)
71}
72
73pub fn app_name(comm: &str, cgroup: Option<&str>, exe: Option<&str>) -> String {
74    if let Some(name) = cgroup.and_then(scope_app_name) {
75        return name;
76    }
77    if let Some(path) = exe {
78        let base = path.rsplit('/').next().unwrap_or(path);
79        let base = base.trim_end_matches(" (deleted)");
80        if !base.is_empty() {
81            return base.to_string();
82        }
83    }
84    comm.to_string()
85}
86
87/// One group per app, biggest PSS first.
88pub fn group(
89    rows: &[ProcRow],
90    pss: &HashMap<u32, PssInfo>,
91    pid_cgroup: &HashMap<u32, String>,
92    pid_exe: &HashMap<u32, String>,
93) -> Vec<AppGroup> {
94    let mut groups: HashMap<String, AppGroup> = HashMap::new();
95    for row in rows {
96        let name = app_name(
97            &row.comm,
98            pid_cgroup.get(&row.pid).map(String::as_str),
99            pid_exe.get(&row.pid).map(String::as_str),
100        );
101        let g = groups.entry(name.clone()).or_insert_with(|| AppGroup {
102            name,
103            ..Default::default()
104        });
105        g.procs += 1;
106        g.rss_kb += row.rss_kb;
107        g.pids.push(row.pid);
108        if let Some(info) = pss.get(&row.pid) {
109            g.pss_kb += info.rollup.pss_kb;
110            g.uss_kb += info.rollup.uss_kb;
111        }
112    }
113    let mut out: Vec<AppGroup> = groups.into_values().collect();
114    for g in &mut out {
115        g.pids.sort_unstable();
116    }
117    sort_groups(&mut out);
118    out
119}
120
121fn sort_groups(groups: &mut [AppGroup]) {
122    groups.sort_by(|a, b| b.pss_kb.cmp(&a.pss_kb).then_with(|| a.name.cmp(&b.name)));
123}
124
125/// Fold everything below `min_share` of the total into one "others" tile, so
126/// the map does not dissolve into slivers (327 apps, top 12 = 89%).
127pub fn collapse(groups: Vec<AppGroup>, min_share: f64) -> Vec<AppGroup> {
128    let total: u64 = groups.iter().map(|g| g.pss_kb).sum();
129    if total == 0 || !(0.0..1.0).contains(&min_share) {
130        return groups;
131    }
132    let threshold = (total as f64 * min_share) as u64;
133    let mut out = Vec::with_capacity(groups.len());
134    let mut others = AppGroup {
135        name: String::new(),
136        synthetic: true,
137        ..Default::default()
138    };
139    let mut hidden = 0usize;
140    for g in groups {
141        if g.pss_kb >= threshold {
142            out.push(g);
143        } else {
144            hidden += 1;
145            others.pss_kb += g.pss_kb;
146            others.uss_kb += g.uss_kb;
147            others.rss_kb += g.rss_kb;
148            others.procs += g.procs;
149        }
150    }
151    if hidden > 0 {
152        others.name = format!("others ({hidden})");
153        out.push(others);
154    }
155    sort_groups(&mut out);
156    out
157}
158
159fn worst_ratio(row: &[f64], side: f64) -> f64 {
160    let sum: f64 = row.iter().sum();
161    let max = row.iter().cloned().fold(0.0_f64, f64::max);
162    let min = row.iter().cloned().fold(f64::INFINITY, f64::min);
163    (side * side * max / (sum * sum)).max(sum * sum / (side * side * min))
164}
165
166fn rect_from(x0: f64, y0: f64, x1: f64, y1: f64) -> Rect {
167    let x = x0.round() as u16;
168    let y = y0.round() as u16;
169    let right = x1.round() as u16;
170    let bottom = y1.round() as u16;
171    Rect::new(x, y, right.saturating_sub(x), bottom.saturating_sub(y))
172}
173
174/// Squarified treemap: area proportional to `values`, tiles as square as the
175/// arithmetic allows. `values` must be sorted descending (as `group` returns).
176pub fn squarify(values: &[u64], area: Rect) -> Vec<Rect> {
177    let mut out = vec![Rect::new(area.x, area.y, 0, 0); values.len()];
178    let total: u64 = values.iter().sum();
179    if total == 0 || area.width < 2 || area.height < 2 {
180        return out;
181    }
182    let scale = (area.width as f64 * area.height as f64) / total as f64;
183    let (mut x, mut y) = (area.x as f64, area.y as f64);
184    let (mut w, mut h) = (area.width as f64, area.height as f64);
185    let mut i = 0usize;
186    while i < values.len() && w >= 1.0 && h >= 1.0 {
187        let side = w.min(h);
188        let mut row: Vec<f64> = vec![values[i] as f64 * scale];
189        let mut best = worst_ratio(&row, side);
190        let mut j = i + 1;
191        while j < values.len() {
192            let mut cand = row.clone();
193            cand.push(values[j] as f64 * scale);
194            let score = worst_ratio(&cand, side);
195            if score > best {
196                break;
197            }
198            best = score;
199            row = cand;
200            j += 1;
201        }
202        let row_sum: f64 = row.iter().sum();
203        if w >= h {
204            let thickness = (row_sum / h).min(w);
205            let mut yy = y;
206            for (k, a) in row.iter().enumerate() {
207                let rh = if k + 1 == row.len() {
208                    y + h - yy
209                } else {
210                    a / thickness.max(f64::EPSILON)
211                };
212                out[i + k] = rect_from(x, yy, x + thickness, yy + rh);
213                yy += rh;
214            }
215            x += thickness;
216            w -= thickness;
217        } else {
218            let thickness = (row_sum / w).min(h);
219            let mut xx = x;
220            for (k, a) in row.iter().enumerate() {
221                let rw = if k + 1 == row.len() {
222                    x + w - xx
223                } else {
224                    a / thickness.max(f64::EPSILON)
225                };
226                out[i + k] = rect_from(xx, y, xx + rw, y + thickness);
227                xx += rw;
228            }
229            y += thickness;
230            h -= thickness;
231        }
232        i += j - i;
233    }
234    out
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240    use crate::procfs::Rollup;
241
242    fn row(pid: u32, comm: &str, rss: u64) -> ProcRow {
243        ProcRow {
244            pid,
245            comm: comm.to_string(),
246            rss_kb: rss,
247            delta_kb: 0,
248        }
249    }
250
251    fn info(pss: u64, uss: u64) -> PssInfo {
252        PssInfo {
253            rollup: Rollup {
254                pss_kb: pss,
255                uss_kb: uss,
256                ..Default::default()
257            },
258            at: std::time::Instant::now(),
259        }
260    }
261
262    #[test]
263    fn scope_names_lose_prefix_pid_and_escapes() {
264        assert_eq!(
265            app_name(
266                "chrome",
267                Some("/user.slice/app-com.google.Chrome-391949.scope"),
268                None
269            ),
270            "com.google.Chrome"
271        );
272        assert_eq!(
273            app_name(
274                "sing-box",
275                Some("/user.slice/app-gnome-sing\\x2dbox-482443.scope"),
276                None
277            ),
278            "gnome-sing-box"
279        );
280        // A scope without a numeric tail is kept as is.
281        assert_eq!(app_name("x", Some("/a/app-plain.scope"), None), "plain");
282    }
283
284    #[test]
285    fn non_scope_cgroups_fall_back_to_exe_then_comm() {
286        assert_eq!(
287            app_name(
288                "node",
289                Some("/user.slice/session-2.scope"),
290                Some("/usr/bin/node-22")
291            ),
292            "node-22"
293        );
294        assert_eq!(
295            app_name(
296                "codex",
297                Some("/user.slice"),
298                Some("/usr/bin/codex (deleted)")
299            ),
300            "codex"
301        );
302        assert_eq!(app_name("kworker/0:1", Some("/"), None), "kworker/0:1");
303    }
304
305    #[test]
306    fn processes_merge_into_one_app_across_scopes() {
307        let rows = [
308            row(1, "chrome", 100),
309            row(2, "chrome", 200),
310            row(3, "chrome", 300),
311        ];
312        let pss = HashMap::from([(1, info(10, 5)), (2, info(20, 6)), (3, info(30, 7))]);
313        let cg = HashMap::from([
314            (1, "/app-com.google.Chrome-1.scope".to_string()),
315            (2, "/app-com.google.Chrome-2.scope".to_string()),
316            (3, "/app-com.google.Chrome-3.scope".to_string()),
317        ]);
318        let groups = group(&rows, &pss, &cg, &HashMap::new());
319        assert_eq!(groups.len(), 1);
320        assert_eq!(groups[0].name, "com.google.Chrome");
321        assert_eq!(groups[0].procs, 3);
322        assert_eq!(groups[0].pss_kb, 60);
323        assert_eq!(groups[0].uss_kb, 18);
324        assert_eq!(groups[0].pids, vec![1, 2, 3]);
325    }
326
327    #[test]
328    fn groups_are_sorted_by_pss_and_ignore_missing_pss() {
329        let rows = [row(1, "a", 100), row(2, "b", 900), row(3, "c", 50)];
330        let pss = HashMap::from([(1, info(500, 0)), (2, info(100, 0))]);
331        let groups = group(&rows, &pss, &HashMap::new(), &HashMap::new());
332        let names: Vec<&str> = groups.iter().map(|g| g.name.as_str()).collect();
333        assert_eq!(names, vec!["a", "b", "c"]);
334        assert_eq!(groups[2].pss_kb, 0, "missing PSS must not be invented");
335    }
336
337    #[test]
338    fn collapse_folds_the_long_tail_and_preserves_totals() {
339        let mut groups: Vec<AppGroup> = (0..12)
340            .map(|i| AppGroup {
341                name: format!("g{i}"),
342                pss_kb: if i == 0 { 5000 } else { 10 },
343                uss_kb: 10,
344                rss_kb: 20,
345                procs: 1,
346                pids: vec![i as u32],
347                synthetic: false,
348            })
349            .collect();
350        sort_groups(&mut groups);
351        let total: u64 = groups.iter().map(|g| g.pss_kb).sum();
352        let collapsed = collapse(groups, 0.01); // 1% of 5110 ≈ 51 kB
353        assert_eq!(collapsed.len(), 2, "one big app plus others");
354        assert!(collapsed[1].synthetic);
355        assert_eq!(collapsed[1].name, "others (11)");
356        assert_eq!(
357            collapsed.iter().map(|g| g.pss_kb).sum::<u64>(),
358            total,
359            "collapse must not lose memory"
360        );
361    }
362
363    fn overlap(a: Rect, b: Rect) -> u32 {
364        let x = a.right().min(b.right()).saturating_sub(a.x.max(b.x));
365        let y = a.bottom().min(b.bottom()).saturating_sub(a.y.max(b.y));
366        u32::from(x) * u32::from(y)
367    }
368
369    #[test]
370    fn treemap_tiles_stay_inside_and_do_not_overlap() {
371        let values = [5000u64, 2500, 1200, 700, 300, 100, 50, 20, 10];
372        let area = Rect::new(0, 0, 120, 40);
373        let rects = squarify(&values, area);
374        assert_eq!(rects.len(), values.len());
375        for r in &rects {
376            assert!(
377                r.right() <= area.right() && r.bottom() <= area.bottom(),
378                "{r:?}"
379            );
380        }
381        for i in 0..rects.len() {
382            for j in i + 1..rects.len() {
383                assert!(
384                    overlap(rects[i], rects[j]) <= 1,
385                    "{:?} vs {:?}",
386                    rects[i],
387                    rects[j]
388                );
389            }
390        }
391        // Areas track values: the biggest tile holds the biggest share.
392        let tile_area = |r: Rect| u32::from(r.width) * u32::from(r.height);
393        assert!(tile_area(rects[0]) > tile_area(rects[1]));
394        assert!(tile_area(rects[1]) > tile_area(rects[2]));
395    }
396
397    #[test]
398    fn treemap_area_is_proportional_within_a_few_percent() {
399        let values = [60u64, 30, 10];
400        let area = Rect::new(10, 5, 100, 50);
401        let rects = squarify(&values, area);
402        let total: f64 = 100.0;
403        let container = 100.0 * 50.0;
404        for (r, v) in rects.iter().zip(values.iter()) {
405            let got = f64::from(r.width) * f64::from(r.height);
406            let want = container * (*v as f64) / total;
407            let err = (got - want).abs() / want;
408            assert!(err < 0.15, "tile {r:?} area {got} vs {want}");
409        }
410    }
411
412    #[test]
413    fn treemap_handles_degenerate_input() {
414        assert!(squarify(&[], Rect::new(0, 0, 10, 10)).is_empty());
415        assert_eq!(squarify(&[0, 0], Rect::new(0, 0, 10, 10))[0].width, 0);
416        assert_eq!(
417            squarify(&[5], Rect::new(2, 3, 20, 10))[0],
418            Rect::new(2, 3, 20, 10)
419        );
420    }
421}