pub mod graph;
use std::sync::Mutex;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Cell, Clear, Paragraph, Row, Table};
use ratatui::Frame;
use crate::app::{
fmt_dur, fmt_interval, local_time_str, App, BOX_CONNS, BOX_DISKIO, BOX_DISKS, BOX_LAN, BOX_NET,
BOX_PROCS, IoGraphMode, LayoutMode, MenuState,
};
use crate::collect::conn::{sock_str, Conn, ConnFilter, ConnSort};
use crate::collect::disk::TreeNode;
use crate::collect::lan::Neighbor;
use crate::config::{Config, Lang};
use crate::theme::*;
use graph::{braille_bar, braille_graph};
pub use graph::GraphMode;
const GRAPH_FLOOR: f64 = 64.0 * 1024.0; pub(crate) const THEME_VISIBLE: usize = 14;
static BOX_AREAS: Mutex<Vec<(usize, Rect)>> = Mutex::new(Vec::new());
pub fn hit_box(col: u16, row: u16) -> Option<usize> {
BOX_AREAS
.lock()
.unwrap()
.iter()
.find(|(_, r)| col >= r.x && col < r.x + r.width && row >= r.y && row < r.y + r.height)
.map(|(i, _)| *i)
}
pub fn box_rect(idx: usize) -> Option<Rect> {
BOX_AREAS
.lock()
.unwrap()
.iter()
.find(|(i, _)| *i == idx)
.map(|(_, r)| *r)
}
pub fn draw(f: &mut Frame, app: &App) {
let area = f.area();
if let Some(bg) = bg() {
f.render_widget(Block::new().style(Style::new().bg(bg)), area);
}
BOX_AREAS.lock().unwrap().clear();
let outer = Layout::vertical([Constraint::Min(0), Constraint::Length(1)]).split(area);
let graph_ids: Vec<usize> = [BOX_NET, BOX_DISKIO]
.into_iter()
.filter(|&i| app.visible[i])
.collect();
let table_ids: Vec<usize> = [BOX_LAN, BOX_CONNS, BOX_PROCS, BOX_DISKS]
.into_iter()
.filter(|&i| app.visible[i])
.collect();
match (graph_ids.is_empty(), table_ids.is_empty()) {
(false, false) => match app.layout {
LayoutMode::Classic => {
let (graphs_w, _) = split_horizontal(outer[0].width, 76, 40);
let main = Layout::horizontal([
Constraint::Length(graphs_w),
Constraint::Fill(1),
])
.split(outer[0]);
draw_stack(f, main[0], app, &graph_ids, true);
draw_list_stack(f, main[1], app, &table_ids, true);
}
LayoutMode::Wide | LayoutMode::Tall => {
let stacked_graphs = app.layout == LayoutMode::Tall;
let graph_min = GRAPH_MIN_ROWS * if stacked_graphs { graph_ids.len() as u16 } else { 1 };
let ideal = tables_ideal_h(app, &table_ids, outer[0].width);
let (g_desired, t_desired) = split_vertical(outer[0].height, graph_min, ideal);
let hs = VERT_ALLOC.lock().unwrap().update(
vec![g_desired, t_desired],
outer[0].height,
std::time::Instant::now(),
);
let graphs_h = hs.first().copied().unwrap_or(g_desired);
let main = Layout::vertical([
Constraint::Length(graphs_h),
Constraint::Fill(1),
])
.split(outer[0]);
if stacked_graphs {
draw_stack(f, main[0], app, &graph_ids, true);
} else {
draw_row(f, main[0], app, &graph_ids);
}
draw_table_grid(f, main[1], app, &table_ids);
}
},
(false, true) => draw_stack(f, outer[0], app, &graph_ids, app.layout == LayoutMode::Tall),
(true, false) => draw_table_grid(f, outer[0], app, &table_ids),
(true, true) => {}
}
match app.menu {
MenuState::None => draw_footer(f, outer[1], app),
MenuState::Search => {
let cols =
Layout::horizontal([Constraint::Min(0), Constraint::Length(9)]).split(outer[1]);
let target = if app.search_box == BOX_PROCS {
"procs"
} else {
"conns"
};
let q = &app.search_buf;
let mut spans = vec![
Span::styled("[/] ", Style::new().fg(hi())),
Span::styled(
format!("{q}▏ "),
Style::new().fg(if q.is_empty() {
palette().dim
} else {
palette().text
}),
),
];
spans.extend(footer_key("tab", target));
spans.extend(footer_key("enter", app.lang.tr("filter")));
spans.extend(footer_key("esc", app.lang.tr("clear")));
f.render_widget(Paragraph::new(Line::from(spans)), cols[0]);
f.render_widget(
Paragraph::new(Line::from(Span::styled(
format!("{} ", local_time_str()),
Style::new().fg(accent()),
))),
cols[1],
);
}
MenuState::Main(sel) => draw_menu_footer(f, outer[1], sel, app.lang),
MenuState::Theme(sel, scroll) => {
draw_menu_footer(f, outer[1], 0, app.lang);
draw_theme_popup(f, outer[0], sel, scroll);
}
MenuState::Settings(sel) => {
draw_menu_footer(f, outer[1], 1, app.lang);
draw_settings_popup(f, outer[0], app, sel);
}
MenuState::Reset(sel) => {
draw_menu_footer(f, outer[1], 2, app.lang);
draw_reset_popup(f, outer[0], sel, app.lang);
}
MenuState::Graphs => {
draw_menu_footer(f, outer[1], 3, app.lang);
draw_graphs_popup(f, outer[0], app);
}
MenuState::Help => {
draw_menu_footer(f, outer[1], 4, app.lang);
draw_help_popup(f, outer[0], app);
}
MenuState::Detail(b, id) => {
draw_menu_footer(f, outer[1], 0, app.lang);
draw_detail_popup(f, outer[0], app, b, id);
}
MenuState::ConfirmKill(pid) => {
draw_menu_footer(f, outer[1], 0, app.lang);
draw_confirm_popup(f, outer[0], app, pid, false);
}
MenuState::ConfirmRestart(pid) => {
draw_menu_footer(f, outer[1], 0, app.lang);
draw_confirm_popup(f, outer[0], app, pid, true);
}
}
}
fn draw_stack(f: &mut Frame, area: Rect, app: &App, ids: &[usize], fill: bool) {
if ids.is_empty() {
return;
}
let cons: Vec<Constraint> = if fill {
vec![Constraint::Fill(1); ids.len()]
} else {
ids.iter()
.map(|&i| {
if i == BOX_NET {
Constraint::Percentage(58)
} else {
Constraint::Percentage(42)
}
})
.collect()
};
let parts = Layout::vertical(cons).split(area);
for (&i, r) in ids.iter().zip(parts.iter()) {
draw_box(f, *r, app, i);
}
}
fn draw_row(f: &mut Frame, area: Rect, app: &App, ids: &[usize]) {
if ids.is_empty() {
return;
}
let cons = vec![Constraint::Fill(1); ids.len()];
let parts = Layout::horizontal(cons).split(area);
for (&i, r) in ids.iter().zip(parts.iter()) {
draw_box(f, *r, app, i);
}
}
fn draw_box(f: &mut Frame, area: Rect, app: &App, idx: usize) {
match idx {
BOX_NET => draw_net(f, area, app, app.focus[BOX_NET]),
BOX_LAN => draw_lan(f, area, app, app.focus[BOX_LAN]),
BOX_DISKIO => draw_diskio(f, area, app, app.focus[BOX_DISKIO]),
BOX_DISKS => draw_disks(f, area, app, app.focus[BOX_DISKS]),
BOX_CONNS => draw_conns(f, area, app, app.focus[BOX_CONNS]),
BOX_PROCS => draw_procs(f, area, app, app.focus[BOX_PROCS]),
_ => {}
}
}
fn boxed(
f: &mut Frame,
area: Rect,
title: Line<'static>,
border: Color,
badge: usize,
focused: bool,
) -> Rect {
let block = Block::bordered()
.border_type(BorderType::Rounded)
.style(Style::new().bg(bg().unwrap_or(Color::Reset)))
.border_style(Style::new().fg(if focused { hi() } else { border }))
.title(title);
let inner = block.inner(area);
f.render_widget(block, area);
BOX_AREAS.lock().unwrap().push((badge - 1, area));
inner
}
const GRAPH_MIN_ROWS: u16 = 4;
const LIST_MAX_ROWS: u16 = 12;
const TABLE_GRID_MIN_W: u16 = 100;
struct StableAlloc {
applied: Vec<u16>,
total: u16,
last: Option<std::time::Instant>,
}
impl StableAlloc {
const fn new() -> Self {
Self {
applied: Vec::new(),
total: 0,
last: None,
}
}
fn update(&mut self, desired: Vec<u16>, total: u16, now: std::time::Instant) -> Vec<u16> {
const MIN_DELTA: i32 = 4;
const SETTLE: std::time::Duration = std::time::Duration::from_secs(3);
let reset = self.applied.len() != desired.len() || self.total != total;
if reset || self.last.is_none() {
self.applied = desired;
self.total = total;
self.last = Some(now);
return self.applied.clone();
}
if now.duration_since(self.last.unwrap_or(now)) >= SETTLE {
let moved = desired
.iter()
.zip(&self.applied)
.any(|(d, a)| (*d as i32 - *a as i32).abs() >= MIN_DELTA);
if moved && desired.iter().sum::<u16>() == total {
self.applied = desired;
self.last = Some(now);
}
}
self.applied.clone()
}
}
static LIST_ALLOC: Mutex<StableAlloc> = Mutex::new(StableAlloc::new());
static VERT_ALLOC: Mutex<StableAlloc> = Mutex::new(StableAlloc::new());
static LIST_ALLOC_TOP: Mutex<StableAlloc> = Mutex::new(StableAlloc::new());
const LAN_BOX_MAX_ROWS: u16 = 6;
static LIST_ALLOC_BOTTOM: Mutex<StableAlloc> = Mutex::new(StableAlloc::new());
fn alloc_heights(ideals: &[u16], total: u16, spare_to: &[usize]) -> Vec<u16> {
let n = ideals.len();
if n == 0 {
return Vec::new();
}
let sum: u16 = ideals.iter().sum();
let mut out = ideals.to_vec();
if total >= sum {
let spare = total - sum;
let targets: Vec<usize> = if spare_to.is_empty() {
(0..n).collect()
} else {
spare_to.iter().copied().filter(|&i| i < n).collect()
};
if !targets.is_empty() {
let base = spare / targets.len() as u16;
let rem = spare % targets.len() as u16;
for (k, &i) in targets.iter().enumerate() {
out[i] += base + u16::from((k as u16) < rem);
}
}
let used: u16 = out.iter().sum();
if let Some(last) = out.last_mut() {
*last += total.saturating_sub(used);
}
return out;
}
let min_each = 3u16;
if total <= min_each * n as u16 {
return vec![(total / n as u16).max(1); n];
}
let usable = total - min_each * n as u16;
let flex: u32 = ideals.iter().map(|h| h.saturating_sub(min_each) as u32).sum();
let mut out = vec![min_each; n];
if flex > 0 {
let mut assigned = 0u16;
for (i, &h) in ideals.iter().enumerate() {
let share = (h.saturating_sub(min_each) as u32)
.saturating_mul(usable as u32)
.saturating_div(flex) as u16;
out[i] += share;
assigned += share;
}
let rem = usable - assigned;
let biggest = ideals
.iter()
.enumerate()
.max_by_key(|(_, &h)| h)
.map(|(i, _)| i)
.unwrap_or(0);
out[biggest] += rem;
}
out
}
fn split_horizontal(w: u16, need: u16, graph_min: u16) -> (u16, u16) {
let tables = (w / 2).max(need.min(w.saturating_sub(graph_min)));
(w.saturating_sub(tables), tables)
}
fn split_vertical(h: u16, graph_min: u16, tables_ideal: u16) -> (u16, u16) {
let graph_cap = h / 2;
let tables = if h.saturating_sub(tables_ideal) > graph_cap {
h - graph_cap
} else {
tables_ideal.clamp(3, h.saturating_sub(graph_min).max(3))
};
(h.saturating_sub(tables), tables)
}
fn list_ideal_rows(rows: usize) -> u16 {
let h = ((rows as u16).saturating_add(3)).clamp(4, LIST_MAX_ROWS);
(h + 1) & !1
}
fn box_ideal_rows(app: &App, idx: usize) -> u16 {
match idx {
BOX_LAN => list_ideal_rows(app.lan.neighbors.len()),
BOX_CONNS => list_ideal_rows(app.conn.conns.len()),
BOX_PROCS => list_ideal_rows(app.proc.procs.len()),
BOX_DISKS => list_ideal_rows(app.disk.tree.len() * 2),
_ => GRAPH_MIN_ROWS,
}
}
fn tables_ideal_h(app: &App, ids: &[usize], width: u16) -> u16 {
if ids.is_empty() {
return 0;
}
if width < TABLE_GRID_MIN_W {
return ids.iter().map(|&i| box_ideal_rows(app, i)).sum();
}
ids.chunks(2)
.map(|pair| pair.iter().map(|&i| box_ideal_rows(app, i)).max().unwrap_or(0))
.sum()
}
fn fit_columns(
base: &[usize],
flex: usize,
flex_min: usize,
flex_max: usize,
total: u16,
spacing: usize,
) -> Vec<Constraint> {
let n = base.len();
if n == 0 {
return Vec::new();
}
let avail = (total as usize).saturating_sub(spacing * n.saturating_sub(1));
let fixed: usize = base
.iter()
.enumerate()
.filter(|(i, _)| *i != flex)
.map(|(_, w)| *w)
.sum();
let room = avail.saturating_sub(fixed);
let mut want = base.to_vec();
want[flex] = if room >= flex_min {
room.min(flex_max.max(flex_min))
} else {
flex_min
};
let base_sum: usize = want.iter().sum();
if base_sum > avail {
return want.iter().map(|&w| Constraint::Length(w as u16)).collect();
}
let max_grow: Vec<usize> = want.iter().map(|&w| (w / 2).max(2)).collect();
let mut grow = vec![0usize; n];
let mut slack = avail - base_sum;
let mut progressed = true;
while slack > 0 && progressed {
progressed = false;
for i in 0..n {
if slack == 0 {
break;
}
if grow[i] < max_grow[i] {
grow[i] += 1;
slack -= 1;
progressed = true;
}
}
}
want.iter()
.zip(&grow)
.map(|(&w, &g)| Constraint::Length((w + g) as u16))
.collect()
}
fn draw_table_grid(f: &mut Frame, area: Rect, app: &App, ids: &[usize]) {
if ids.is_empty() {
return;
}
let grid = area.width >= TABLE_GRID_MIN_W && ids.len() > 1;
if !grid {
draw_list_stack(f, area, app, ids, false);
return;
}
let row_ideals: Vec<u16> = ids
.chunks(2)
.map(|pair| pair.iter().map(|&i| box_ideal_rows(app, i)).max().unwrap_or(4))
.collect();
let spare_rows: Vec<usize> = row_ideals
.iter()
.enumerate()
.map(|(r, _)| {
ids[r * 2..(r * 2 + 2).min(ids.len())]
.iter()
.position(|&i| matches!(i, BOX_CONNS | BOX_PROCS))
.unwrap_or(0)
})
.collect();
let desired = alloc_heights(&row_ideals, area.height, &spare_rows);
let hs = LIST_ALLOC
.lock()
.unwrap()
.update(desired, area.height, std::time::Instant::now());
let cons: Vec<Constraint> = hs.iter().map(|&h| Constraint::Length(h)).collect();
let rows = Layout::vertical(cons).split(area);
for (pair, r) in ids.chunks(2).zip(rows.iter()) {
if pair.len() == 1 {
draw_box(f, *r, app, pair[0]);
} else {
let cols =
Layout::horizontal([Constraint::Fill(1), Constraint::Fill(1)]).split(*r);
draw_box(f, cols[0], app, pair[0]);
draw_box(f, cols[1], app, pair[1]);
}
}
}
fn draw_list_stack(f: &mut Frame, area: Rect, app: &App, ids: &[usize], snap_mid: bool) {
if snap_mid {
let bi = ids
.iter()
.position(|&i| !matches!(i, BOX_LAN | BOX_CONNS))
.unwrap_or(ids.len());
if bi > 0 && bi < ids.len() {
let parts =
Layout::vertical([Constraint::Fill(1), Constraint::Fill(1)]).split(area);
if ids[0] == BOX_LAN && ids.len() > 2 {
let lan_h = box_ideal_rows(app, BOX_LAN)
.min(LAN_BOX_MAX_ROWS)
.clamp(
1,
(parts[0].height.saturating_sub(3)).clamp(1, LAN_BOX_MAX_ROWS),
);
let sub = Layout::vertical([Constraint::Length(lan_h), Constraint::Fill(1)])
.split(parts[0]);
draw_box(f, sub[0], app, ids[0]);
draw_table_group(f, sub[1], app, &ids[1..bi], &LIST_ALLOC_TOP);
} else {
draw_table_group(f, parts[0], app, &ids[..bi], &LIST_ALLOC_TOP);
}
draw_table_group(f, parts[1], app, &ids[bi..], &LIST_ALLOC_BOTTOM);
return;
}
}
draw_table_group(f, area, app, ids, &LIST_ALLOC);
}
fn draw_table_group(
f: &mut Frame,
area: Rect,
app: &App,
ids: &[usize],
alloc: &Mutex<StableAlloc>,
) {
if ids.is_empty() || area.height == 0 {
return;
}
let ideals: Vec<u16> = ids.iter().map(|&i| box_ideal_rows(app, i)).collect();
let spare_to: Vec<usize> = ids
.iter()
.enumerate()
.filter(|&(_, id)| matches!(*id, BOX_CONNS | BOX_PROCS))
.map(|(i, _)| i)
.collect();
let desired = alloc_heights(&ideals, area.height, &spare_to);
let hs = alloc
.lock()
.unwrap()
.update(desired, area.height, std::time::Instant::now());
let cons: Vec<Constraint> = hs.iter().map(|&h| Constraint::Length(h)).collect();
let parts = Layout::vertical(cons).split(area);
for (&id, r) in ids.iter().zip(parts.iter()) {
draw_box(f, *r, app, id);
}
}
fn title_line(
badge: usize,
word: &str,
key: char,
pieces: Vec<Vec<Span<'static>>>,
border: Color,
focused: bool,
) -> Line<'static> {
let frame = if focused { hi() } else { border };
let b = Style::new().fg(frame);
let mut spans: Vec<Span> = vec![Span::styled("─", b), Span::styled("┐", b)];
if badge > 0 {
spans.push(Span::styled(superscript(badge), bold(hi())));
}
match word.find(key) {
Some(pos) => {
let (head, tail) = word.split_at(pos);
let (k, tail) = tail.split_at(1);
spans.push(Span::styled(head.to_string(), bold(palette().title)));
spans.push(Span::styled(k.to_string(), bold(hi())));
spans.push(Span::styled(tail.to_string(), bold(palette().title)));
}
None => spans.push(Span::styled(word.to_string(), bold(palette().title))),
}
spans.push(Span::styled("┌", b));
for p in pieces {
spans.push(Span::styled("─", b));
spans.push(Span::styled("┐", b));
spans.extend(p);
spans.push(Span::styled("┌", b));
}
Line::from(spans)
}
fn text_s(s: String) -> Span<'static> {
Span::styled(s, text())
}
fn key_span(k: &str) -> Span<'static> {
Span::styled(k.to_string(), bold(hi()))
}
fn fword(key: char, word: &str, value: &str) -> Vec<Span<'static>> {
let mut v = Vec::new();
match word.find(key) {
Some(pos) => {
let (head, tail) = word.split_at(pos);
let (k, tail) = tail.split_at(1);
v.push(Span::styled(head.to_string(), Style::new().fg(palette().title)));
v.push(Span::styled(k.to_string(), bold(hi())));
v.push(Span::styled(tail.to_string(), Style::new().fg(palette().title)));
}
None => v.push(Span::styled(word.to_string(), Style::new().fg(palette().title))),
}
if !value.is_empty() {
v.push(Span::styled(format!(": {value}"), Style::new().fg(palette().title)));
}
v
}
fn scroll_hint(list_len: usize, off: usize, area: Rect) -> String {
let visible = area.height.saturating_sub(3); let hidden = list_len.saturating_sub(off + visible as usize);
if hidden > 0 {
format!("+{hidden}")
} else {
String::new()
}
}
fn superscript(n: usize) -> String {
const SUP: [char; 10] = ['⁰', '¹', '²', '³', '⁴', '⁵', '⁶', '⁷', '⁸', '⁹'];
n.to_string()
.chars()
.map(|c| SUP[c.to_digit(10).unwrap_or(0) as usize])
.collect()
}
fn contrast_fg(c: Color) -> Color {
match c {
Color::Rgb(r, g, b) => {
let l = 0.2126 * r as f32 + 0.7152 * g as f32 + 0.0722 * b as f32;
if l > 140.0 {
Color::Rgb(0, 0, 0)
} else {
Color::Rgb(255, 255, 255)
}
}
_ => Color::Black,
}
}
fn track_bg(slot: usize) -> Color {
if slot.is_multiple_of(2) {
download().at(1.0)
} else {
upload().at(1.0)
}
}
fn track_fg(slot: usize) -> Color {
contrast_fg(track_bg(slot))
}
pub fn clamped_offset(app: &App, idx: usize, visible: usize) -> usize {
app.scroll[idx].min(list_len(app, idx).saturating_sub(visible.max(1)))
}
pub fn list_len(app: &App, idx: usize) -> usize {
match idx {
BOX_LAN => app.lan.neighbors.len(),
BOX_CONNS => conn_items(app).len(),
BOX_PROCS => procs_display(app).len(),
BOX_DISKS => {
let mut flat: Vec<(&TreeNode, String)> = Vec::new();
emit_tree_rows(&app.disk.tree, "", 0, &mut flat);
flat.len()
}
_ => 0,
}
}
fn name_matches(name: &str, q: &str) -> bool {
q.is_empty() || name.to_lowercase().contains(&q.to_lowercase())
}
#[derive(Clone, Copy, Default)]
pub struct GroupInfo {
pub n: usize,
pub rx: u64,
pub tx: u64,
pub rr: f64,
pub rs: f64,
}
pub enum ConnItem<'a> {
Agg {
key: String,
name: String,
rep: &'a Conn,
info: GroupInfo,
},
Row {
c: &'a Conn,
child: bool,
},
}
impl ConnItem<'_> {
pub fn id(&self) -> u64 {
match self {
Self::Row { c, .. } => c.inode,
Self::Agg { key, .. } => {
use std::hash::{Hash, Hasher};
let mut h = std::collections::hash_map::DefaultHasher::new();
key.hash(&mut h);
0x8000_0000_0000_0000 | (h.finish() & 0x7fff_ffff_ffff_ffff)
}
}
}
pub fn is_agg(&self) -> bool {
matches!(self, Self::Agg { .. })
}
pub fn conn(&self) -> Option<&Conn> {
match self {
Self::Row { c, .. } => Some(c),
_ => None,
}
}
}
pub fn conn_items(app: &App) -> Vec<ConnItem<'_>> {
let list = conns_display(app);
if app.conn.sort != ConnSort::Proc {
return list
.into_iter()
.map(|c| ConnItem::Row { c, child: false })
.collect();
}
let expand_all = !app.search.is_empty();
let group_open = |key: &str| -> bool {
app.proc_expand_default != app.expanded.contains(key)
};
let mut out: Vec<ConnItem> = Vec::new();
let mut i = 0;
while i < list.len() {
let key = crate::collect::conn::owner_key(list[i]);
let n = list[i..]
.iter()
.take_while(|c| crate::collect::conn::owner_key(c) == key)
.count();
if n == 1 {
out.push(ConnItem::Row {
c: list[i],
child: false,
});
i += 1;
continue;
}
let group = &list[i..i + n];
let info = GroupInfo {
n,
rx: group.iter().map(|c| c.bytes_recv).sum(),
tx: group.iter().map(|c| c.bytes_sent).sum(),
rr: group.iter().map(|c| c.rate_recv).sum(),
rs: group.iter().map(|c| c.rate_sent).sum(),
};
let expanded = expand_all || group_open(&key);
out.push(ConnItem::Agg {
key: key.clone(),
name: key.clone(),
rep: group[0],
info,
});
if expanded {
out.extend(group.iter().map(|c| ConnItem::Row {
c,
child: true,
}));
}
i += n;
}
out
}
pub fn selected_agg_key(app: &App, idx: usize) -> Option<String> {
match conn_items(app).get(app.sel[idx]?) {
Some(ConnItem::Agg { key, .. }) => Some(key.clone()),
_ => None,
}
}
pub fn selected_is_agg(app: &App, idx: usize) -> bool {
idx == BOX_CONNS
&& app.sel[idx].is_some()
&& conn_items(app)
.get(app.sel[idx].unwrap())
.is_some_and(|i| i.is_agg())
}
pub fn group_is_open(app: &App, key: &str) -> bool {
app.proc_expand_default != app.expanded.contains(key)
}
pub fn set_group_open(app: &mut App, key: &str, open: bool) {
if open != app.proc_expand_default {
app.expanded.insert(key.to_string());
} else {
app.expanded.remove(key);
}
}
pub fn toggle_group(app: &mut App, key: &str) {
let open = group_is_open(app, key);
set_group_open(app, key, !open);
}
pub fn procs_display(app: &App) -> Vec<&crate::collect::proc::ProcRow> {
let mut out = Vec::new();
for pid in &app.tracked.procs {
if let Some(p) = app.proc.procs.iter().find(|p| p.pid == *pid) {
out.push(p);
}
}
for p in app.proc.procs.iter() {
if !app.tracked.procs.contains(&p.pid)
&& (app.search_box != BOX_PROCS || name_matches(&p.name, &app.search))
{
out.push(p);
}
}
out
}
pub fn conns_display(app: &App) -> Vec<&Conn> {
let mut out = Vec::new();
for ino in &app.tracked.conns {
if let Some(c) = app.conn.conns.iter().find(|c| c.inode == *ino) {
out.push(c);
}
}
for c in app.conn.conns.iter() {
if !app.tracked.conns.contains(&c.inode) {
out.push(c);
}
}
let mut out = match app.conn.filter {
ConnFilter::All => out,
ConnFilter::Lan => out
.into_iter()
.filter(|c| matches!(c.remote.0, std::net::IpAddr::V4(v4) if v4.is_private()))
.collect(),
ConnFilter::Tcp => out.into_iter().filter(|c| c.is_tcp()).collect(),
ConnFilter::Udp => out.into_iter().filter(|c| !c.is_tcp()).collect(),
};
if let Some(ip) = app.conn.peer_filter {
out.retain(|c| c.remote.0 == std::net::IpAddr::V4(ip));
}
if app.search_box == BOX_CONNS && !app.search.is_empty() {
let q = app.search.to_lowercase();
out.retain(|c| {
c.proc
.as_deref()
.unwrap_or("")
.to_lowercase()
.contains(&q)
});
}
out
}
pub fn conn_list(app: &App) -> Vec<&Conn> {
conns_display(app)
}
pub fn selected_id(app: &App, idx: usize) -> Option<u64> {
match idx {
BOX_PROCS => procs_display(app).get(app.sel[BOX_PROCS]?).map(|p| p.pid as u64),
BOX_LAN => app
.lan
.sorted_neighbors()
.get(app.sel[BOX_LAN]?)
.map(|n| u32::from(n.ip) as u64),
BOX_CONNS => conn_items(app)
.get(app.sel[BOX_CONNS]?)
.map(|i| i.id()),
_ => None,
}
}
pub fn selected_pid(app: &App, idx: usize) -> Option<u32> {
match idx {
BOX_PROCS => procs_display(app).get(app.sel[BOX_PROCS]?).map(|p| p.pid),
BOX_CONNS => conn_items(app)
.get(app.sel[BOX_CONNS]?)
.and_then(|i| i.conn())
.and_then(|c| c.pid),
_ => None,
}
}
pub fn toggle_track(app: &mut App, idx: usize, id: u64) {
match idx {
BOX_PROCS => app.tracked.toggle_proc(id as u32),
BOX_CONNS => app.tracked.toggle_conn(id),
_ => {}
}
}
pub fn box_capacity(idx: usize) -> usize {
BOX_AREAS
.lock()
.unwrap()
.iter()
.find(|(i, _)| *i == idx)
.map(|(_, r)| (r.height.saturating_sub(3)).max(1) as usize)
.unwrap_or(10)
}
pub fn reselect(app: &mut App, idx: usize, id: u64) {
let pos = match idx {
BOX_PROCS => procs_display(app).iter().position(|p| p.pid as u64 == id),
BOX_LAN => app
.lan
.sorted_neighbors()
.iter()
.position(|n| u32::from(n.ip) as u64 == id),
BOX_CONNS => conn_items(app).iter().position(|i| i.id() == id),
_ => None,
};
app.sel[idx] = pos;
if let Some(n) = pos {
let cap = box_capacity(idx);
let off = &mut app.scroll[idx];
if n < *off {
*off = n;
} else if n + 1 >= *off + cap {
*off = (n + 1).saturating_sub(cap);
}
}
}
pub fn move_selection(app: &mut App, idx: usize, delta: i32) {
let len = list_len(app, idx);
if len == 0 {
return;
}
let cap = box_capacity(idx);
let next = match app.sel[idx] {
None => Some(if delta < 0 { len - 1 } else { 0 }),
Some(cur) => Some((cur as i32 + delta).clamp(0, len as i32 - 1) as usize),
};
app.sel[idx] = next;
if let Some(n) = next {
let off = &mut app.scroll[idx];
if n < *off {
*off = n;
} else if n + 1 >= *off + cap {
*off = (n + 1).saturating_sub(cap);
}
}
}
fn draw_net(f: &mut Frame, area: Rect, app: &App, focused: bool) {
let name = app
.net
.selected
.clone()
.unwrap_or_else(|| "-".to_string());
let rest = vec![
vec![text_s(app.hostname.clone())],
vec![text_s(name.clone())],
vec![
key_span("-"),
text_s("refresh ".to_string()),
text_s(fmt_interval(app.tick)),
key_span("+"),
],
];
let inner = boxed(
f,
area,
title_line(BOX_NET + 1, "net", 'n', rest, border_net(), focused),
border_net(),
BOX_NET + 1,
focused,
);
if inner.width < 10 || inner.height < 4 {
return;
}
let chunks = Layout::vertical([
Constraint::Length(1),
Constraint::Length(1),
Constraint::Min(3),
Constraint::Length(1),
Constraint::Min(3),
])
.split(inner);
let mut info: Vec<Span> = vec![Span::styled(" ", dim())];
if let Some(i) = app.net.ifaces.get(&name) {
let (mark, col) = if i.operstate == "up" {
("▲ up", hi())
} else {
("▼ down", alert_end())
};
info.push(Span::styled(format!("{mark} "), Style::new().fg(col)));
if let Some(s) = i.speed_mbps {
info.push(Span::styled(format!("{s}Mb/s "), Style::new().fg(accent())));
}
if let Some(d) = &i.duplex {
info.push(Span::styled(
format!("{} ", if d == "full" { "FD" } else { "HD" }),
dim(),
));
}
if let Some(m) = i.mtu {
info.push(Span::styled(format!("mtu {m} "), dim()));
}
if let Some(a) = i.addrs.first() {
info.push(Span::styled(a.clone(), Style::new().fg(accent())));
}
if i.addrs.len() > 1 {
info.push(Span::styled(format!(" +{}", i.addrs.len() - 1), dim()));
}
}
f.render_widget(Paragraph::new(Line::from(info)), chunks[0]);
let rates = app.net.selected_rates();
let (hrx, htx) = app.net.selected_hist();
let rx_head = Line::from(vec![
Span::styled(" ▼ RX ", bold(download().at(0.5))),
Span::styled(
rates.map(|r| fmt_speed(r.rx)).unwrap_or_else(|| "…".into()),
bold(download().at(0.5)),
),
Span::styled(" Σ ", dim()),
Span::styled(
rates.map(|r| fmt_bytes(r.rx_total as f64)).unwrap_or_default(),
text(),
),
]);
let tx_head = Line::from(vec![
Span::styled(" ▲ TX ", bold(upload().at(0.5))),
Span::styled(
rates.map(|r| fmt_speed(r.tx)).unwrap_or_else(|| "…".into()),
bold(upload().at(0.5)),
),
Span::styled(" Σ ", dim()),
Span::styled(
rates.map(|r| fmt_bytes(r.tx_total as f64)).unwrap_or_default(),
text(),
),
]);
f.render_widget(Paragraph::new(rx_head), chunks[1]);
f.render_widget(
Paragraph::new(braille_graph(
&hrx,
chunks[2].width as usize,
chunks[2].height as usize,
GRAPH_FLOOR,
download(),
app.graph_net,
)),
chunks[2],
);
f.render_widget(Paragraph::new(tx_head), chunks[3]);
f.render_widget(
Paragraph::new(braille_graph(
&htx,
chunks[4].width as usize,
chunks[4].height as usize,
GRAPH_FLOOR,
upload(),
app.graph_net,
)),
chunks[4],
);
}
fn draw_lan(f: &mut Frame, area: Rect, app: &App, focused: bool) {
let list = app.lan.sorted_neighbors();
let subnets = app
.lan
.subnets
.iter()
.map(|(_, n, p)| format!("{n}/{p}"))
.collect::<Vec<_>>()
.join(" ");
let sweep = if app.lan.sweeping {
"scanning…"
} else if app.lan.sweep_enabled {
"on"
} else {
"off"
};
let per_remote = app.conn.per_remote_v4();
let visible = area.height.saturating_sub(3).max(1) as usize;
let off = clamped_offset(app, BOX_LAN, visible);
let sel = if focused { app.sel[BOX_LAN] } else { None };
let mut rest = vec![
vec![text_s(subnets)],
vec![text_s(format!("{} hosts", list.len()))],
fword('s', "sweep", sweep),
fword('e', "order", app.lan.sort.label()),
];
let sh = scroll_hint(list.len(), off, area);
if !sh.is_empty() {
rest.push(vec![text_s(sh)]);
}
let inner = boxed(
f,
area,
title_line(BOX_LAN + 1, "lan", 'l', rest, border_lan(), focused),
border_lan(),
BOX_LAN + 1,
focused,
);
if inner.width < 10 || inner.height < 2 {
return;
}
let headers = ["IP", "MAC", "HOSTNAME", "IF"];
let visible = inner.height.saturating_sub(1) as usize;
let rows: Vec<Row> = list
.iter()
.enumerate()
.skip(off)
.take(visible)
.map(|(i, nb)| {
let pinned = app.lan.tracked.contains(&nb.ip);
let selected = sel == Some(i);
let alt = (i - off) % 2 == 1;
neighbor_row(
nb,
&app.lan.resolve_failures,
per_remote.get(&nb.ip),
pinned,
selected,
alt,
)
})
.collect();
let header = Row::new(headers).style(dim().add_modifier(Modifier::BOLD));
let cols = fit_columns(&[16, 17, 0, 8], 2, 8, 30, inner.width, 1);
let table = Table::new(rows, cols).header(header).column_spacing(1);
f.render_widget(table, inner);
}
fn neighbor_row(
nb: &Neighbor,
resolve_failures: &std::collections::HashSet<std::net::Ipv4Addr>,
conns: Option<&(usize, f64, f64, u64, u64)>,
pinned: bool,
selected: bool,
alt: bool,
) -> Row<'static> {
let (marker, color) = if nb.is_gateway {
("✦", hi())
} else if nb.is_self {
("·", accent())
} else {
(" ", palette().text)
};
let host = match &nb.hostname {
Some(h) => (h.clone(), palette().text),
None if resolve_failures.contains(&nb.ip) => ("—".to_string(), palette().dim),
None => ("resolving…".to_string(), palette().dim),
};
let host_text = host.0.clone();
let (bg, base_fg) = if pinned {
(Some(track_bg(0)), contrast_fg(track_bg(0)))
} else if selected {
(Some(track_bg(alt as usize)), contrast_fg(track_bg(alt as usize)))
} else {
(None, palette().text)
};
let fg = |col: Color| if bg.is_some() { base_fg } else { col };
let mut host_cell = Line::from(Span::styled(host_text.clone(), fg(host.1)));
if let Some((n, r, _, tr, _)) = conns {
if *n > 0 {
let extra = format!(" ·{n}conn {}", fmt_speed(*r));
let sum = if *tr > 0 {
format!(" Σ{}", fmt_bytes(*tr as f64))
} else {
String::new()
};
host_cell = Line::from(vec![
Span::styled(host_text, fg(host.1)),
Span::styled(extra, fg(hi())),
Span::styled(sum, fg(hi())),
]);
}
}
let style = match bg {
Some(c) => Style::new().fg(base_fg).bg(c),
None => Style::new().fg(base_fg),
};
let mac_plain = nb.mac.clone().unwrap_or_else(|| "expired".into());
Row::new([
Cell::from(Line::from(vec![
Span::styled(marker.to_string(), fg(color)),
Span::styled(nb.ip.to_string(), fg(color)),
])),
Cell::from(Span::styled(mac_plain, fg(palette().text))),
Cell::from(host_cell),
Cell::from(Span::styled(nb.iface.clone(), fg(palette().text))),
])
.style(style)
}
fn draw_diskio(f: &mut Frame, area: Rect, app: &App, focused: bool) {
let (tr, tw, ti, sr, sw) = app.disk.totals();
let rest = vec![
vec![text_s(format!("{:.0} iop/s", ti))],
vec![text_s(format!("mode {}", app.io_graph.label()))],
];
let inner = boxed(
f,
area,
title_line(BOX_DISKIO + 1, "disk i/o", 'i', rest, border_disk(), focused),
border_disk(),
BOX_DISKIO + 1,
focused,
);
if inner.width < 16 || inner.height < 4 {
return;
}
let (hr, hw) = app.disk.hist();
match app.io_graph {
IoGraphMode::Both => {
let g = Layout::vertical([Constraint::Percentage(50), Constraint::Percentage(50)])
.split(inner);
graph_section(f, g[0], " ▼ READ ", download(), &hr, tr, sr, app.graph_disk);
graph_section(f, g[1], " ▲ WRITE ", upload(), &hw, tw, sw, app.graph_disk);
}
IoGraphMode::Read => graph_section(f, inner, " ▼ READ ", download(), &hr, tr, sr, app.graph_disk),
IoGraphMode::Write => graph_section(f, inner, " ▲ WRITE ", upload(), &hw, tw, sw, app.graph_disk),
}
}
#[allow(clippy::too_many_arguments)]
fn graph_section(
f: &mut Frame,
area: Rect,
label: &str,
grad: Gradient,
data: &[f64],
total: f64,
sum: u64,
mode: GraphMode,
) {
let g = Layout::vertical([Constraint::Length(1), Constraint::Min(2)]).split(area);
f.render_widget(
Paragraph::new(Line::from(vec![
Span::styled(label, bold(grad.at(0.5))),
Span::styled(fmt_speed(total), bold(grad.at(0.5))),
Span::styled(" Σ ", dim()),
Span::styled(fmt_bytes(sum as f64), text()),
])),
g[0],
);
f.render_widget(
Paragraph::new(braille_graph(
data,
g[1].width as usize,
g[1].height as usize,
GRAPH_FLOOR,
grad,
mode,
)),
g[1],
);
}
fn draw_disks(f: &mut Frame, area: Rect, app: &App, focused: bool) {
let mut flat: Vec<(&TreeNode, String)> = Vec::new();
emit_tree_rows(&app.disk.tree, "", 0, &mut flat);
let off = app.scroll[BOX_DISKS].min(flat.len().saturating_sub(1));
let mut rest = vec![
vec![text_s(format!("{} dev", app.disk.devices.len()))],
vec![text_s(format!(
"mounts: {}",
if app.disks_expanded { "all" } else { "first" }
))],
];
let sh = scroll_hint(flat.len(), off, area);
if !sh.is_empty() {
rest.push(vec![text_s(sh)]);
}
let inner = boxed(
f,
area,
title_line(BOX_DISKS + 1, "disks", 'd', rest, border_disk(), focused),
border_disk(),
BOX_DISKS + 1,
focused,
);
if inner.width < 16 || inner.height < 2 {
return;
}
let rows: Vec<Row> = flat
.into_iter()
.skip(off)
.map(|(node, label)| disk_row(app, node, label))
.collect();
let headers = ["DEV", "USED", "R/S", "W/S"];
let header = Row::new(headers).style(dim().add_modifier(Modifier::BOLD));
let cols = fit_columns(&[0, 16, 9, 9], 0, 10, 40, inner.width, 1);
let table = Table::new(rows, cols).header(header).column_spacing(1);
f.render_widget(table, inner);
}
fn disk_row(app: &App, node: &TreeNode, mut label: String) -> Row<'static> {
let dev = app.disk.dev_by_name(&node.name);
match dev {
Some(d) => {
if let Some(p) = &d.pretty {
label.push_str(&format!(" ({p})"));
}
if let Some(m) = d.mounts.first() {
if app.disks_expanded {
label.push_str(&format!(" {}", d.mounts.join(" ")));
} else {
label.push_str(&format!(" {m}"));
if d.mounts.len() > 1 {
label.push_str(&format!(" +{}", d.mounts.len() - 1));
}
}
}
}
None => {
if let Some(p) = &node.pretty {
label.push_str(&format!(" ({p})"));
}
}
}
let usage = if let Some(d) = dev {
let frac = if d.total > 0 {
d.used as f64 / d.total as f64
} else {
0.0
};
Line::from(vec![
braille_bar(frac, 10, palette().used.at(frac as f32)),
Span::styled(format!(" {:>3.0}%", frac * 100.0), text()),
])
} else if let Some(sz) = node.size {
Line::from(Span::styled(fmt_bytes(sz as f64), text()))
} else {
Line::from(Span::styled("", dim()))
};
let rate_r = dev.map(|d| fmt_speed(d.rate_r)).unwrap_or_default();
let rate_w = dev.map(|d| fmt_speed(d.rate_w)).unwrap_or_default();
Row::new([
Cell::from(Span::styled(label, text())),
Cell::from(usage),
Cell::from(Span::styled(rate_r, Style::new().fg(download().at(0.5)))),
Cell::from(Span::styled(rate_w, Style::new().fg(upload().at(0.5)))),
])
}
fn proc_group_detail(name: &str, info: GroupInfo) -> Vec<Line<'static>> {
let k = dim();
let line1 = vec![
Span::styled(format!(" {} ×{} ", name, info.n), bold(accent())),
Span::styled(" Σ ", k),
Span::styled(
format!(
"{}{} {}{} ",
'\u{2193}',
fmt_bytes(info.rx as f64),
'\u{2191}',
fmt_bytes(info.tx as f64)
),
text(),
),
Span::styled("rate ", k),
Span::styled(
format!(
"{}{}/s {}{}/s",
'\u{2193}',
fmt_speed(info.rr),
'\u{2191}',
fmt_speed(info.rs)
),
text(),
),
];
vec![Line::from(line1)]
}
fn conn_row_aggregate(
name: &str,
n: usize,
open: bool,
rx: u64,
tx: u64,
slot: Option<usize>,
) -> Row<'static> {
if open {
let bg = match slot {
Some(sl) => track_bg(sl % 2),
None => track_bg(0),
};
let cell = |s: String| {
Cell::from(Span::styled(s, Style::new().fg(palette().text).bg(bg)))
};
Row::new([
cell(format!("\u{25be}{name} ×{n} Σ")),
cell("-".into()),
cell("-".into()),
cell(format!("{n} conns")),
cell(fmt_bytes(rx as f64)),
cell(fmt_bytes(tx as f64)),
])
.style(Style::new().bg(bg))
} else {
let paint = |col: Color| slot.map(track_fg).unwrap_or(col);
Row::new([
Cell::from(Line::from(vec![
Span::styled(
format!("\u{25b8}{name} ×{n}"),
Style::new().fg(paint(accent())),
),
Span::styled(" Σ", Style::new().fg(paint(palette().dim))),
])),
Cell::from(Span::styled(
"-",
Style::new().fg(paint(palette().dim)),
)),
Cell::from(Span::styled(
"-",
Style::new().fg(paint(palette().dim)),
)),
Cell::from(Span::styled(
format!("{n} conns"),
Style::new().fg(paint(accent())),
)),
Cell::from(Span::styled(
fmt_bytes(rx as f64),
Style::new().fg(paint(download().at(0.5))),
)),
Cell::from(Span::styled(
fmt_bytes(tx as f64),
Style::new().fg(paint(upload().at(0.5))),
)),
])
}
}
fn draw_conns(f: &mut Frame, area: Rect, app: &App, focused: bool) {
let filter = app.conn.filter;
let items = conn_items(app);
let visible = area.height.saturating_sub(3).max(1) as usize;
let off = clamped_offset(app, BOX_CONNS, visible);
let sel = if focused { app.sel[BOX_CONNS] } else { None };
let mut rest = vec![
vec![text_s(format!("{}", items.len()))],
fword('f', "filter", filter.label()),
fword('o', "order", app.conn.sort.label()),
];
let sh = scroll_hint(items.len(), off, area);
if !sh.is_empty() {
rest.push(vec![text_s(sh)]);
}
let inner = boxed(
f,
area,
title_line(BOX_CONNS + 1, "conns", 'c', rest, border_lan(), focused),
border_lan(),
BOX_CONNS + 1,
focused,
);
if inner.width < 16 || inner.height < 2 {
return;
}
let total_mode = matches!(app.conn.sort, ConnSort::Sum | ConnSort::Proc);
let headers = if total_mode {
["NAME", "PID", "LOCAL", "REMOTE", "\u{3a3} RX", "\u{3a3} TX"]
} else {
["NAME", "PID", "LOCAL", "REMOTE", "RX/S", "TX/S"]
};
let mut rows: Vec<Row> = Vec::new();
let mut sel_y = None;
for (i, item) in items.iter().enumerate().skip(off).take(visible) {
let id = item.id();
let slot = app.tracked.conn_slot(id);
let mut row = match item {
ConnItem::Agg { name, info, .. } => {
conn_row_aggregate(
name,
info.n,
group_is_open(app, name),
info.rx,
info.tx,
slot,
)
}
ConnItem::Row { c, child } => conn_row(c, app, slot, *child),
};
if sel == Some(i) {
row = row.height(2);
sel_y = Some(inner.y + 1 + (i - off) as u16);
}
rows.push(row);
}
let header = Row::new(headers).style(dim().add_modifier(Modifier::BOLD));
let cols = fit_columns(&[0, 7, 18, 18, 9, 9], 0, 12, 24, inner.width, 1);
let table = Table::new(rows, cols).header(header).column_spacing(1);
f.render_widget(table, inner);
if let (Some(y), Some(si)) = (sel_y, sel) {
if let Some(item) = items.get(si) {
if let Some(rect) = overlay_rect(inner, y) {
let lines = match item {
ConnItem::Agg { name, info, .. } => {
proc_group_detail(name, *info)
}
ConnItem::Row { c, .. } => conn_detail(c, app),
};
draw_selected(f, rect, lines);
}
}
}
}
fn overlay_rect(inner: Rect, y: u16) -> Option<Rect> {
if y < inner.y || y >= inner.bottom() {
return None; }
Some(Rect {
x: inner.x,
y,
width: inner.width,
height: 2.min(inner.bottom() - y),
})
}
fn draw_selected(f: &mut Frame, rect: Rect, lines: Vec<Line<'static>>) {
let bgc = palette().hi;
let fg = contrast_fg(bgc);
f.render_widget(Clear, rect);
let mut ls: Vec<Line> = lines.into_iter().take(2).collect();
while ls.len() < 2 {
ls.push(Line::from(""));
}
f.render_widget(
Paragraph::new(ls).style(Style::new().bg(bgc).fg(fg)),
rect,
);
}
fn conn_detail(c: &Conn, app: &App) -> Vec<Line<'static>> {
let name = c.proc.clone().unwrap_or_else(|| app.conn.user_name(c.uid));
let pid = c.pid.map(|p| p.to_string()).unwrap_or_else(|| "-".into());
let mut state = if c.is_listen() {
"tcp LISTEN".to_string()
} else if c.is_tcp() {
"tcp ESTAB".to_string()
} else {
"udp".to_string()
};
if c.dead {
state.push_str(" closed");
}
let k = Style::new().fg(palette().dim);
let dl = download().at(0.5);
let up = upload().at(0.5);
let (local_s, remote_s) = if c.is_listen() {
(sock_str(&c.local), "—".to_string())
} else {
(sock_str(&c.local), sock_str(&c.remote))
};
vec![
Line::from(vec![
Span::styled(format!(" {} ", name), bold(accent())),
Span::styled(format!("(pid {}) ", pid), dim()),
Span::styled(format!("{state} ",), text()),
Span::styled("inode ", k),
Span::styled(c.inode.to_string(), text()),
Span::styled(
match c.first_seen {
Some(fs) => {
let end = c.dead_at.unwrap_or_else(std::time::Instant::now);
format!(
" {} {}",
app.lang.tr("lifetime"),
fmt_dur(end.duration_since(fs).as_secs())
)
}
_ => String::new(),
},
dim(),
),
]),
Line::from(vec![
Span::styled(format!("{} ", local_s), text()),
Span::styled("→ ".to_string(), k),
Span::styled(format!("{} ", remote_s), text()),
Span::styled("↓ ", Style::new().fg(dl)),
Span::styled(format!("{} ", fmt_bytes(c.bytes_recv as f64)), Style::new().fg(dl)),
Span::styled(format!("({}) ", fmt_speed(c.rate_recv)), dim()),
Span::styled("↑ ", Style::new().fg(up)),
Span::styled(format!("{} ", fmt_bytes(c.bytes_sent as f64)), Style::new().fg(up)),
Span::styled(format!("({})", fmt_speed(c.rate_sent)), dim()),
]),
]
}
fn conn_row(
c: &Conn,
app: &App,
slot: Option<usize>,
child: bool,
) -> Row<'static> {
let dim_all = c.dead;
let paint = |col: Color| {
if dim_all {
palette().dim
} else {
slot.map(track_fg).unwrap_or(col)
}
};
let sum_mode = matches!(app.conn.sort, ConnSort::Sum | ConnSort::Proc);
let proc_str = match &c.proc {
Some(n) => n.clone(),
None => app.conn.user_name(c.uid),
};
let pid_str = c.pid.map(|p| p.to_string()).unwrap_or_else(|| "-".into());
let proc_color = if c.proc.is_some() {
accent()
} else {
palette().dim
};
let label = if c.is_listen() {
"\u{25e6}tcp"
} else if c.is_tcp() {
"tcp"
} else {
"udp"
};
let (local_s, remote_s) = if c.is_listen() {
(sock_str(&c.local), "—".to_string())
} else {
(sock_str(&c.local), sock_str(&c.remote))
};
let mark = "";
let (r_cell, w_cell) = if sum_mode {
(
fmt_bytes(c.bytes_recv as f64),
fmt_bytes(c.bytes_sent as f64),
)
} else {
(fmt_speed(c.rate_recv), fmt_speed(c.rate_sent))
};
let rx = format!("{mark}{r_cell}");
let tx = format!("{mark}{w_cell}");
let indent = if child { " " } else { "" };
Row::new([
Cell::from(Line::from(vec![
Span::styled(format!("{indent}{proc_str}"), Style::new().fg(paint(proc_color))),
Span::styled(
format!(" {label}"),
Style::new().fg(paint(palette().dim)),
),
])),
Cell::from(Span::styled(pid_str, Style::new().fg(paint(palette().dim)))),
Cell::from(Span::styled(local_s, Style::new().fg(paint(palette().text)))),
Cell::from(Span::styled(remote_s, Style::new().fg(paint(palette().text)))),
Cell::from(Span::styled(rx, Style::new().fg(paint(download().at(0.5))))),
Cell::from(Span::styled(tx, Style::new().fg(paint(upload().at(0.5))))),
])
.style(match slot {
Some(sl) => Style::new().bg(track_bg(sl)),
None => Style::new(),
})
}
fn draw_procs(f: &mut Frame, area: Rect, app: &App, focused: bool) {
let list = procs_display(app);
let visible = area.height.saturating_sub(3).max(1) as usize;
let off = clamped_offset(app, BOX_PROCS, visible);
let sel = if focused { app.sel[BOX_PROCS] } else { None };
let mut rest = vec![
vec![text_s(format!("{} procs", app.proc.procs.len()))],
fword('r', "order", app.proc.sort.label()),
];
if app.proc.is_root {
rest.push(vec![text_s("root".to_string())]);
}
if app.monlog.enabled {
rest.push(vec![Span::styled("● rec", bold(hi()))]);
}
if app.udp.fresh {
rest.push(vec![Span::styled("udp", bold(hi()))]);
}
let sh = scroll_hint(list.len(), off, area);
if !sh.is_empty() {
rest.push(vec![text_s(sh)]);
}
let inner = boxed(
f,
area,
title_line(BOX_PROCS + 1, "procs", 'p', rest, border_lan(), focused),
border_lan(),
BOX_PROCS + 1,
focused,
);
if inner.width < 16 || inner.height < 2 {
return;
}
let headers = [
"NAME", "PID", "Σ NET↓", "Σ NET↑", "↓/s", "↑/s", "DISK ΣR", "DISK ΣW",
];
let mut rows: Vec<Row> = Vec::new();
let mut sel_y = None;
let list = procs_display(app);
for (i, p) in list.iter().enumerate().skip(off).take(visible) {
let slot = app.tracked.proc_slot(p.pid);
let paint = |col: Color| slot.map(track_fg).unwrap_or(col);
let cells = [p.name.clone(),
p.pid.to_string(),
fmt_bytes(p.net_recv as f64),
fmt_bytes(p.net_sent as f64),
fmt_speed(p.net_rr),
fmt_speed(p.net_sr),
fmt_bytes(p.disk_r as f64),
fmt_bytes(p.disk_w as f64)];
let mut row = Row::new([
Cell::from(Span::styled(
cells[0].clone(),
Style::new().fg(paint(if p.alive {
palette().text
} else {
palette().dim
})),
)),
Cell::from(Span::styled(cells[1].clone(), Style::new().fg(paint(palette().text)))),
Cell::from(Span::styled(cells[2].clone(), Style::new().fg(paint(download().at(0.5))))),
Cell::from(Span::styled(cells[3].clone(), Style::new().fg(paint(upload().at(0.5))))),
Cell::from(Span::styled(cells[4].clone(), Style::new().fg(paint(download().at(0.5))))),
Cell::from(Span::styled(cells[5].clone(), Style::new().fg(paint(upload().at(0.5))))),
Cell::from(Span::styled(cells[6].clone(), Style::new().fg(paint(download().at(1.0))))),
Cell::from(Span::styled(cells[7].clone(), Style::new().fg(paint(upload().at(1.0))))),
])
.style(match slot {
Some(sl) => Style::new().bg(track_bg(sl)),
None => Style::new(),
});
if sel == Some(i) {
row = row.height(2);
sel_y = Some(inner.y + 1 + (i - off) as u16);
}
rows.push(row);
}
let header = Row::new(headers).style(dim().add_modifier(Modifier::BOLD));
let cols = fit_columns(&[0, 7, 7, 7, 9, 9, 7, 7], 0, 8, 24, inner.width, 1);
let table = Table::new(rows, cols).header(header).column_spacing(1);
f.render_widget(table, inner);
if let (Some(y), Some(si)) = (sel_y, sel) {
if let Some(p) = list.get(si) {
if let Some(rect) = overlay_rect(inner, y) {
draw_selected(f, rect, proc_detail(p, app.lang));
}
}
}
}
fn proc_detail(
p: &crate::collect::proc::ProcRow,
lang: crate::config::Lang,
) -> Vec<Line<'static>> {
let cmd = std::fs::read(format!("/proc/{}/cmdline", p.pid))
.ok()
.map(|b| {
let s: String = b
.split(|&c| c == 0)
.filter(|s| !s.is_empty())
.map(|s| String::from_utf8_lossy(s).into_owned())
.collect::<Vec<_>>()
.join(" ");
s
})
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "-".to_string());
let k = Style::new().fg(palette().dim);
let dl = download().at(0.5);
let up = upload().at(0.5);
let arrows = ['\u{2193}', '\u{2191}'];
vec![
Line::from(vec![
Span::styled(format!(" {} ", p.name), bold(accent())),
Span::styled(format!("(pid {}) ", p.pid), dim()),
Span::styled(
match p.uptime_s {
Some(s) => format!("{} {} ", lang.tr("uptime"), fmt_dur(s)),
None => String::new(),
},
dim(),
),
Span::styled("net ", k),
Span::styled(
format!("{}{} ", arrows[0], fmt_bytes(p.net_recv as f64)),
Style::new().fg(dl),
),
Span::styled(
format!("{}{} ", arrows[1], fmt_bytes(p.net_sent as f64)),
Style::new().fg(up),
),
Span::styled("rate ", k),
Span::styled(
format!("{}{} ", arrows[0], fmt_speed(p.net_rr)),
Style::new().fg(dl),
),
Span::styled(
format!("{}{}", arrows[1], fmt_speed(p.net_sr)),
Style::new().fg(up),
),
Span::styled(" udp ", k),
Span::styled(
format!(
"{}Σ{} {}{} ",
arrows[0],
fmt_bytes(p.udp_recv as f64),
arrows[1],
fmt_bytes(p.udp_sent as f64)
),
Style::new().fg(dl),
),
Span::styled(
format!(
"{}{}/s {}{}/s",
arrows[0],
fmt_speed(p.udp_rr),
arrows[1],
fmt_speed(p.udp_sr)
),
Style::new().fg(up),
),
]),
Line::from(vec![
Span::styled("disk ", k),
Span::styled(
format!("\u{3a3}R{} ", fmt_bytes(p.disk_r as f64)),
Style::new().fg(dl),
),
Span::styled(
format!("\u{3a3}W{} ", fmt_bytes(p.disk_w as f64)),
Style::new().fg(up),
),
Span::styled("rate ", k),
Span::styled(
format!("R{} ", fmt_speed(p.disk_rr)),
Style::new().fg(dl),
),
Span::styled(
format!("W{}", fmt_speed(p.disk_wr)),
Style::new().fg(up),
),
Span::styled(" cmd ", k),
Span::styled(cmd, text()),
]),
]
}
fn emit_tree_rows<'a>(
nodes: &'a [TreeNode],
prefix: &str,
depth: usize,
out: &mut Vec<(&'a TreeNode, String)>,
) {
let n = nodes.len();
for (i, node) in nodes.iter().enumerate() {
let last = i + 1 == n;
let glyph = if depth == 0 {
String::new()
} else if last {
"└ ".to_string()
} else {
"├ ".to_string()
};
out.push((node, format!("{prefix}{glyph}{}", node.name)));
let branch = if last { " " } else { "│ " };
let child_prefix = if depth == 0 {
String::new()
} else {
format!("{prefix}{branch}")
};
emit_tree_rows(&node.children, &child_prefix, depth + 1, out);
}
}
fn footer_key(k: &str, label: &str) -> Vec<Span<'static>> {
vec![
Span::styled(format!("[{k}]"), Style::new().fg(hi())),
Span::styled(format!(" {label} "), dim()),
]
}
fn draw_footer(f: &mut Frame, area: Rect, app: &App) {
let cols = Layout::horizontal([Constraint::Min(0), Constraint::Length(9)]).split(area);
let key = |k: &str, label: &str| footer_key(k, label);
let lang = app.lang;
let mut spans: Vec<Span> = vec![Span::styled(" ", dim())];
if app.paused {
spans.push(Span::styled(
format!(" ⏸ {} ", app.lang.tr("paused")),
Style::new()
.fg(bg().unwrap_or(Color::Reset))
.bg(hi())
.add_modifier(Modifier::BOLD),
));
}
spans.extend(key("q", "quit"));
spans.extend(key("m", "menu"));
spans.extend(key("space", lang.tr("pause")));
spans.extend(key("/", lang.tr("search")));
spans.extend(key("Tab", &format!("{}:{}", lang.tr("layout"), app.layout.label())));
spans.extend(key("1-6", "boxes"));
spans.extend(key("enter", "detail"));
if app.allow_global_kill {
spans.extend(key("k", "kill"));
}
f.render_widget(Paragraph::new(Line::from(spans)), cols[0]);
f.render_widget(
Paragraph::new(Line::from(Span::styled(
format!("{} ", local_time_str()),
Style::new().fg(accent()),
))),
cols[1],
);
}
fn draw_menu_footer(f: &mut Frame, area: Rect, sel: usize, lang: Lang) {
let labels = ["themes", "settings", "reset", "graphs", "help", "quit", "close"];
let mut spans: Vec<Span> = vec![Span::styled(" ", dim())];
for (i, l) in labels.iter().enumerate() {
let style = if i == sel {
Style::new()
.fg(bg().unwrap_or(Color::Reset))
.bg(hi())
.add_modifier(Modifier::BOLD)
} else {
Style::new().fg(palette().text)
};
spans.push(Span::styled(format!(" {} ", lang.tr(l)), style));
spans.push(Span::styled(" ", dim()));
}
spans.push(Span::styled(lang.tr("hint"), dim()));
f.render_widget(Paragraph::new(Line::from(spans)), area);
}
fn draw_graphs_popup(f: &mut Frame, area: Rect, app: &App) {
let rows = [
("n", "net", app.graph_net.label()),
("d", "disk i/o", app.graph_disk.label()),
("a", "all", "set both"),
];
let (w, h) = (40.min(area.width), 7.min(area.height));
let popup = centered(area, w, h);
f.render_widget(Clear, popup);
let block = Block::bordered()
.border_type(BorderType::Rounded)
.style(Style::new().bg(bg().unwrap_or(Color::Reset)))
.border_style(Style::new().fg(hi()))
.title(title_line(0, "graphs", '\0', vec![], hi(), false));
let inner = block.inner(popup);
f.render_widget(block, popup);
let mut lines: Vec<Line> = rows
.iter()
.map(|(k, word, value)| {
Line::from(vec![
Span::styled(" [", dim()),
Span::styled(k.to_string(), bold(hi())),
Span::styled(format!("] {word}"), text()),
Span::styled(format!(" {value}"), dim()),
])
})
.collect();
lines.push(Line::from(Span::styled(
app.lang.tr("letters_hint"),
dim(),
)));
f.render_widget(Paragraph::new(lines), inner);
}
fn draw_reset_popup(f: &mut Frame, area: Rect, sel: usize, lang: Lang) {
let items = [
("n", "net", lang.tr("reset_net")),
("d", "disk", lang.tr("reset_disk")),
("a", "all", lang.tr("reset_all")),
];
let (w, h) = (34.min(area.width), 5.min(area.height));
let popup = centered(area, w, h);
f.render_widget(Clear, popup);
let block = Block::bordered()
.border_type(BorderType::Rounded)
.style(Style::new().bg(bg().unwrap_or(Color::Reset)))
.border_style(Style::new().fg(hi()))
.title(title_line(0, "reset", '\0', vec![], hi(), false));
let inner = block.inner(popup);
f.render_widget(block, popup);
let lines = items
.iter()
.enumerate()
.map(|(i, (k, word, desc))| {
let style = if i == sel {
Style::new()
.fg(bg().unwrap_or(Color::Reset))
.bg(hi())
.add_modifier(Modifier::BOLD)
} else {
text()
};
Line::from(vec![
Span::styled(" [", dim()),
Span::styled(k.to_string(), Style::new().fg(if i == sel { bg().unwrap_or(Color::Reset) } else { hi() })),
Span::styled(format!("] {word}"), style),
Span::styled(format!(" {desc}"), dim()),
])
})
.collect::<Vec<_>>();
f.render_widget(Paragraph::new(lines), inner);
}
fn draw_settings_popup(f: &mut Frame, area: Rect, app: &App, sel: usize) {
let lang = app.lang;
let retention = if app.monlog.retention_days == 0 {
lang.tr("never").to_string()
} else {
format!("{}d", app.monlog.retention_days)
};
let rows: [(&str, String); 13] = [
(lang.tr("language"), lang.label().to_string()),
(lang.tr("refresh"), fmt_interval(app.tick)),
(lang.tr("layout"), app.layout.label().to_string()),
(lang.tr("net"), app.graph_net.label().to_string()),
(lang.tr("disk"), app.graph_disk.label().to_string()),
(lang.tr("log_interval"), fmt_interval(app.monlog.interval)),
(lang.tr("log_retention"), retention),
(lang.tr("sweep_interval"), fmt_interval(app.lan.sweep_interval)),
(
lang.tr("sweep"),
lang.tr(if app.lan.sweep_enabled { "on" } else { "off" }).to_string(),
),
(
lang.tr("tracked_only"),
lang.tr(if app.log_tracked_only { "on" } else { "off" }).to_string(),
),
(
lang.tr("global_kill"),
lang.tr(if app.allow_global_kill { "on" } else { "off" }).to_string(),
),
(
lang.tr("tombstone"),
if app.conn.tombstone_ttl.is_zero() {
lang.tr("off").to_string()
} else {
fmt_interval(app.conn.tombstone_ttl)
},
),
(
lang.tr("proc_groups"),
lang
.tr(if app.proc_expand_default {
"expanded"
} else {
"collapsed"
})
.to_string(),
),
];
let (w, h) = (60.min(area.width), 19.min(area.height));
let popup = centered(area, w, h);
f.render_widget(Clear, popup);
let block = Block::bordered()
.border_type(BorderType::Rounded)
.style(Style::new().bg(bg().unwrap_or(Color::Reset)))
.border_style(Style::new().fg(hi()))
.title(title_line(0, "settings", '\0', vec![], hi(), false));
let inner = block.inner(popup);
f.render_widget(block, popup);
let mut lines: Vec<Line> = rows
.iter()
.enumerate()
.map(|(i, (label, value))| {
let (ls, vs) = if i == sel {
(
Style::new()
.fg(bg().unwrap_or(Color::Reset))
.bg(hi())
.add_modifier(Modifier::BOLD),
Style::new()
.fg(bg().unwrap_or(Color::Reset))
.bg(hi())
.add_modifier(Modifier::BOLD),
)
} else {
(Style::new().fg(palette().title), text())
};
Line::from(vec![
Span::styled(format!(" {label}: "), ls),
Span::styled(value.clone(), vs),
])
})
.collect();
lines.push(Line::from(Span::styled(lang.tr("hint"), dim())));
if let Some(p) = Config::path() {
let mut path = p.display().to_string();
let prefix = format!(" {}: ", lang.tr("config_path"));
let room = inner.width.saturating_sub(prefix.chars().count() as u16) as usize;
if path.chars().count() > room {
path = format!("…{}", path.chars().skip(path.chars().count() - room.saturating_sub(1)).collect::<String>());
}
lines.push(Line::from(Span::styled(format!("{prefix}{path}"), dim())));
}
f.render_widget(Paragraph::new(lines), inner);
}
type Field = (&'static str, String);
fn proc_status_fields(p: &crate::collect::proc::ProcRow) -> Vec<Field> {
let mut out: Vec<Field> = Vec::new();
let pid = p.pid;
out.push((
"state",
if p.alive { "running".into() } else { "exited".into() },
));
if !p.alive {
if let Some(cmd) = &p.cmdline {
out.push(("cmd", cmd.join(" ")));
out.push(("start", format!("s restarts `{}`", cmd[0])));
}
return out;
}
if let Ok(st) = std::fs::read_to_string(format!("/proc/{pid}/status")) {
let pick = |key: &str, label: &'static str| -> Option<Field> {
st.lines()
.find(|l| l.starts_with(key))
.and_then(|l| l.split_whitespace().nth(1))
.map(|v| (label, v.to_string()))
};
if let Some(f) = pick("Uid:", "uid") {
out.push(f);
}
if let Some(f) = pick("State:", "kstate") {
out.push(f);
}
if let Some(f) = pick("Threads:", "threads") {
out.push(f);
}
if let Some(f) = pick("VmRSS:", "rss") {
out.push((f.0, format!("{} kB", f.1)));
}
}
let exe = std::fs::read_link(format!("/proc/{pid}/exe"))
.map(|p| p.display().to_string())
.unwrap_or_else(|_| "-".into());
out.push(("exe", exe));
let cwd = std::fs::read_link(format!("/proc/{pid}/cwd"))
.map(|p| p.display().to_string())
.unwrap_or_else(|_| "-".into());
out.push(("cwd", cwd));
if let Ok(cmd) = std::fs::read(format!("/proc/{pid}/cmdline")) {
let s: String = cmd
.split(|&c| c == 0)
.filter(|s| !s.is_empty())
.map(|s| String::from_utf8_lossy(s).into_owned())
.collect::<Vec<_>>()
.join(" ");
if !s.is_empty() {
out.push(("cmd", s));
}
}
out
}
fn draw_detail_popup(f: &mut Frame, area: Rect, app: &App, box_idx: usize, id: u64) {
let mut pid: Option<u32> = None;
let mut tracked = false;
let mut fields: Vec<Field> = Vec::new();
let mut gone = String::new();
let mut start_hint = false;
match box_idx {
BOX_PROCS => {
if let Some(p) = app.proc.procs.iter().find(|p| p.pid as u64 == id) {
pid = Some(p.pid);
tracked = app.tracked.proc_slot(p.pid).is_some();
start_hint = p.cmdline.is_some();
fields.push(("name", p.name.clone()));
fields.push(("pid", p.pid.to_string()));
fields.extend(proc_status_fields(p));
fields.push(("net \u{3a3}\u{2193}", fmt_bytes(p.net_recv as f64)));
fields.push(("net \u{3a3}\u{2191}", fmt_bytes(p.net_sent as f64)));
fields.push(("net \u{2193}/s", fmt_speed(p.net_rr)));
fields.push(("net \u{2191}/s", fmt_speed(p.net_sr)));
fields.push(("disk \u{3a3}R", fmt_bytes(p.disk_r as f64)));
fields.push(("disk \u{3a3}W", fmt_bytes(p.disk_w as f64)));
fields.push(("disk R/s", fmt_speed(p.disk_rr)));
fields.push(("disk W/s", fmt_speed(p.disk_wr)));
} else {
gone = format!("process {id} is gone");
}
}
BOX_CONNS => {
if let Some(c) = app.conn.conns.iter().find(|c| c.inode == id) {
pid = c.pid;
tracked = app.tracked.conn_slot(c.inode).is_some();
let state = if c.is_listen() {
"LISTEN"
} else if c.is_tcp() {
"ESTAB"
} else {
"UDP"
};
let proto = if c.is_tcp() { "tcp" } else { "udp" };
fields.push(("name", c.proc.clone().unwrap_or_else(|| app.conn.user_name(c.uid))));
if let Some(p) = c.pid {
fields.push(("pid", p.to_string()));
}
fields.push(("user", app.conn.user_name(c.uid)));
fields.push(("proto", proto.to_string()));
fields.push(("state", state.to_string()));
fields.push(("local", sock_str(&c.local)));
fields.push(("remote", sock_str(&c.remote)));
fields.push(("inode", c.inode.to_string()));
fields.push(("net \u{2193}", fmt_bytes(c.bytes_recv as f64)));
fields.push(("net \u{2191}", fmt_bytes(c.bytes_sent as f64)));
fields.push(("net \u{2193}/s", fmt_speed(c.rate_recv)));
fields.push(("net \u{2191}/s", fmt_speed(c.rate_sent)));
} else {
gone = format!("connection {id} is gone");
}
}
_ => {}
}
let track_hint = if tracked {
"[space] [x] tracked"
} else {
"[space] [ ] track"
};
let mut hints = vec![track_hint.to_string(), "[esc] close".to_string()];
if let Some(p) = pid {
hints.insert(2, format!("[k] kill pid {p}"));
}
if start_hint {
hints.insert(2, "[s] start/restart".to_string());
}
let w = 92.min(area.width);
let lbl_w = fields
.iter()
.map(|(l, _)| l.chars().count())
.max()
.unwrap_or(0);
let inner_w = w.saturating_sub(2) as usize;
let chunk_w = inner_w.saturating_sub(lbl_w + 4).max(10);
let n_lines: usize = gone.len().min(1)
+ fields
.iter()
.map(|(_, v)| wrap_chunks(v, chunk_w).len())
.sum::<usize>();
let h = (n_lines as u16 + 4).min(area.height);
let popup = centered(area, w, h);
f.render_widget(Clear, popup);
let block = Block::bordered()
.border_type(BorderType::Rounded)
.style(Style::new().bg(bg().unwrap_or(Color::Reset)))
.border_style(Style::new().fg(hi()))
.title(title_line(0, "detail", '\0', vec![], hi(), true));
let inner = block.inner(popup);
f.render_widget(block, popup);
let mut all: Vec<Line> = Vec::new();
if !gone.is_empty() {
all.push(Line::from(Span::styled(format!(" {gone}"), dim())));
}
for (label, value) in &fields {
for (i, chunk) in wrap_chunks(value, chunk_w).into_iter().enumerate() {
let indent = if i == 0 {
format!(" {:<lbl_w$} ", label)
} else {
format!(" {:<lbl_w$} ", "")
};
all.push(Line::from(vec![
Span::styled(indent, Style::new().fg(palette().title)),
Span::styled(chunk, text()),
]));
}
}
let hint_lines = pack_rows(&hints, inner.width.saturating_sub(1) as usize);
let hints_h = hint_lines.len() as u16;
let hints_y = inner.bottom().saturating_sub(hints_h);
let fields_h = hints_y.saturating_sub(inner.y);
f.render_widget(
Paragraph::new(all),
Rect { x: inner.x, y: inner.y, width: inner.width, height: fields_h },
);
f.render_widget(
Paragraph::new(
hint_lines
.into_iter()
.map(|l| Line::from(Span::styled(l, bold(hi()))))
.collect::<Vec<_>>(),
),
Rect { x: inner.x, y: hints_y, width: inner.width, height: hints_h },
);
}
fn pack_rows(items: &[String], w: usize) -> Vec<String> {
let mut rows: Vec<String> = Vec::new();
let mut cur = String::new();
for it in items {
let sep = if cur.is_empty() { "" } else { " " };
if !cur.is_empty() && cur.chars().count() + sep.len() + it.chars().count() > w {
rows.push(std::mem::take(&mut cur));
} else {
cur.push_str(sep);
}
cur.push_str(it);
}
if !cur.is_empty() {
rows.push(cur);
}
rows.into_iter().map(|r| format!(" {r}")).collect()
}
fn wrap_chunks(s: &str, w: usize) -> Vec<String> {
if w == 0 {
return vec![s.to_string()];
}
let chars: Vec<char> = s.chars().collect();
if chars.len() <= w {
return vec![s.to_string()];
}
chars
.chunks(w)
.map(|c| c.iter().collect())
.collect()
}
fn draw_confirm_popup(f: &mut Frame, area: Rect, app: &App, pid: u32, restart: bool) {
let name = app
.proc
.procs
.iter()
.find(|p| p.pid == pid)
.map(|p| p.name.clone())
.unwrap_or_else(|| "?".into());
let (w, h) = (52.min(area.width), 7.min(area.height));
let popup = centered(area, w, h);
f.render_widget(Clear, popup);
let block = Block::bordered()
.border_type(BorderType::Rounded)
.style(Style::new().bg(bg().unwrap_or(Color::Reset)))
.border_style(Style::new().fg(alert_end()))
.title(title_line(0, if restart { "restart" } else { "kill" }, '\0', vec![], alert_end(), true));
let inner = block.inner(popup);
f.render_widget(block, popup);
let question = if restart {
format!(" Restart {name} (pid {pid})? SIGTERM, then relaunch its command line.")
} else {
format!(" Send SIGTERM to {name} (pid {pid})?")
};
let lines = vec![
Line::from(question),
Line::from(""),
Line::from(vec![
Span::styled(" [y] ", bold(hi())),
Span::styled("yes ", text()),
Span::styled("[n] ", bold(hi())),
Span::styled("no", text()),
]),
];
f.render_widget(Paragraph::new(lines), inner);
}
fn help_rows(lang: Lang) -> Vec<(String, String)> {
let t = |k: &str| lang.tr(k);
vec![
("1-6".into(), format!("{} / {}", t("boxes"), t("hint_close_short"))),
("Tab".into(), t("layout").to_string()),
("enter".into(), t("detail_desc").to_string()),
("p / c / l".into(), t("focus_desc").to_string()),
("r".into(), t("order_desc").to_string()),
("d".into(), t("expand_desc").to_string()),
("f".into(), t("filter_desc").to_string()),
("o".into(), t("conn_order_desc").to_string()),
("e".into(), t("lan_order_desc").to_string()),
("n / i".into(), t("net_io_desc").to_string()),
("space".into(), t("track_desc").to_string()),
("k".into(), t("kill_desc").to_string()),
("L".into(), t("log_desc").to_string()),
("s".into(), t("sweep_desc").to_string()),
("+ / -".into(), t("refresh_desc").to_string()),
("\u{2191}\u{2193} / wheel".into(), t("sel_scroll_desc").to_string()),
("q / esc / m".into(), t("quit_menu_desc").to_string()),
]
}
fn draw_help_popup(f: &mut Frame, area: Rect, app: &App) {
let rows = help_rows(app.lang);
let w = 62.min(area.width);
let h = ((rows.len() + 8) as u16).min(area.height);
let popup = centered(area, w, h);
f.render_widget(Clear, popup);
let block = Block::bordered()
.border_type(BorderType::Rounded)
.style(Style::new().bg(bg().unwrap_or(Color::Reset)))
.border_style(Style::new().fg(hi()))
.title(title_line(0, "help", '\0', vec![], hi(), false));
let inner = block.inner(popup);
f.render_widget(block, popup);
let mut lines: Vec<Line> = Vec::new();
lines.push(Line::from(vec![
Span::styled(" localist top v0.1.0", bold(accent())),
Span::styled(" by uMaj35ty", dim()),
]));
lines.push(Line::from(Span::styled(
" local list monitor: net / lan / disk io / conns / procs",
dim(),
)));
lines.push(Line::from(Span::styled(
format!(" theme: {}", theme_name()),
dim(),
)));
lines.push(Line::from(Span::styled(
app.lang.tr(if app.udp.fresh { "udp_on" } else { "udp_off" }),
dim(),
)));
lines.push(Line::from(Span::styled(
format!(" {}", app.lang.tr("caliber_head")),
bold(hi()),
)));
for k in ["caliber_procs", "caliber_conns", "caliber_keys"] {
lines.push(Line::from(Span::styled(
app.lang.tr(k),
dim(),
)));
}
lines.push(Line::from(""));
lines.push(Line::from(Span::styled(
" \u{2500}\u{2500} keys \u{2500}\u{2500}",
bold(hi()),
)));
let kw = rows.iter().map(|(k, _)| k.chars().count()).max().unwrap_or(0);
for (k, d) in &rows {
lines.push(Line::from(vec![
Span::styled(format!(" {:<kw$} ", k), bold(hi())),
Span::styled(d.clone(), text()),
]));
}
lines.push(Line::from(""));
lines.push(Line::from(Span::styled(
app.lang.tr("press_any"),
dim(),
)));
f.render_widget(Paragraph::new(lines), inner);
}
fn centered(area: Rect, w: u16, h: u16) -> Rect {
Rect {
x: area.x + (area.width.saturating_sub(w)) / 2,
y: area.y + (area.height.saturating_sub(h)) / 2,
width: w,
height: h,
}
}
fn draw_theme_popup(f: &mut Frame, area: Rect, sel: usize, scroll: usize) {
let count = builtin_count() + 1; let visible = THEME_VISIBLE.min(area.height.saturating_sub(4).max(1) as usize);
let height = visible as u16 + 2;
let width = 30.min(area.width);
let popup = Rect {
x: area.x + 1,
y: area.bottom().saturating_sub(height),
width,
height,
};
let current = theme_name();
let mut lo = scroll.min(count.saturating_sub(visible));
if sel < lo {
lo = sel;
}
if sel >= lo + visible {
lo = sel + 1 - visible;
}
let mut lines: Vec<Line> = Vec::new();
for i in lo..count.min(lo + visible) {
let name = if i == 0 {
"omarchy (current)".to_string()
} else {
builtin_name(i - 1).to_string()
};
let is_current = current == if i == 0 { "omarchy" } else { builtin_name(i - 1) };
let style = if i == sel {
Style::new()
.fg(bg().unwrap_or(Color::Reset))
.bg(hi())
.add_modifier(Modifier::BOLD)
} else if is_current {
Style::new().fg(hi())
} else {
text()
};
let marker = if is_current { "● " } else { " " };
lines.push(Line::from(Span::styled(format!("{marker}{name}"), style)));
}
f.render_widget(Clear, popup);
let block = Block::bordered()
.border_type(BorderType::Rounded)
.style(Style::new().bg(bg().unwrap_or(Color::Reset)))
.border_style(Style::new().fg(hi()))
.title(title_line(0, "theme", '\0', vec![], hi(), false));
let inner = block.inner(popup);
f.render_widget(block, popup);
f.render_widget(Paragraph::new(lines), inner);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::app::BOX_COUNT;
use ratatui::layout::Constraint;
fn lens(cs: &[Constraint]) -> Vec<Option<u16>> {
cs.iter()
.map(|c| match c {
Constraint::Length(n) => Some(*n),
_ => None,
})
.collect()
}
#[test]
fn fit_columns_uses_fixed_vocabulary_widths() {
let cs = fit_columns(&[16, 17, 0, 8], 2, 8, 30, 80, 1);
assert_eq!(lens(&cs), vec![Some(18), Some(19), Some(31), Some(9)]);
let again = fit_columns(&[16, 17, 0, 8], 2, 8, 30, 80, 1);
assert_eq!(lens(&cs), lens(&again));
let narrow = fit_columns(&[16, 17, 0, 8], 2, 8, 30, 40, 1);
assert_eq!(lens(&narrow), vec![Some(16), Some(17), Some(8), Some(8)]);
}
#[test]
fn process_table_width_is_stable_and_capped() {
let base = [0, 7, 7, 7, 9, 9, 7, 7];
assert_eq!(
lens(&fit_columns(&base, 0, 8, 24, 73, 1)),
vec![Some(13), Some(7), Some(7), Some(7), Some(9), Some(9), Some(7), Some(7)]
);
let wide = lens(&fit_columns(&base, 0, 8, 24, 160, 1));
assert_eq!(wide[0], Some(36));
assert_eq!(wide.iter().map(|w| w.unwrap()).sum::<u16>(), 112);
}
#[test]
fn rendered_table_keeps_one_space_between_columns() {
use ratatui::backend::TestBackend;
use ratatui::Terminal;
let headers = ["NAME", "PID", "Σ NET↓", "Σ NET↑", "↓/s", "↑/s", "DISK ΣR", "DISK ΣW"];
let data = [vec![
"zcode-host-local".to_string(),
"546829".to_string(),
"0B".to_string(),
"0B".to_string(),
"0B/s".to_string(),
"0B/s".to_string(),
"20.0KiB".to_string(),
"0B".to_string(),
]];
let cols = fit_columns(&[0, 7, 7, 7, 9, 9, 7, 7], 0, 8, 24, 73, 1);
let mut term = Terminal::new(TestBackend::new(73, 4)).unwrap();
let rows: Vec<Row> = data
.iter()
.map(|r| Row::new(r.iter().map(|c| Cell::from(c.clone())).collect::<Vec<_>>()))
.collect();
let header = Row::new(headers);
term.draw(|f| {
let t = Table::new(rows, cols).header(header).column_spacing(1);
f.render_widget(t, f.area());
})
.unwrap();
let buf = term.backend().buffer();
let line: String = (0..73)
.map(|x| buf[(x, 1)].symbol().to_string())
.collect::<String>();
let fields: Vec<&str> = line.split_whitespace().collect();
assert_eq!(
fields,
vec!["zcode-host-lo", "546829", "0B", "0B", "0B/s", "0B/s", "20.0KiB", "0B"]
);
}
#[test]
fn full_frame_stays_inside_the_terminal() {
use ratatui::backend::TestBackend;
use ratatui::Terminal;
let mut app = crate::app::App::new(None);
app.update();
std::thread::sleep(std::time::Duration::from_millis(700));
app.update();
for (w, h) in [(249u16, 67u16), (80, 24), (120, 30), (200, 50), (60, 20)] {
let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
term.draw(|f| draw(f, &app))
.unwrap_or_else(|e| panic!("{w}x{h}: {e}"));
}
}
#[test]
fn selected_row_overlay_never_leaves_the_buffer() {
use ratatui::backend::TestBackend;
use ratatui::Terminal;
let mut app = crate::app::App::new(None);
app.update();
for i in [BOX_LAN, BOX_CONNS, BOX_DISKS] {
app.visible[i] = false;
}
app.focus[BOX_PROCS] = true;
for k in 0..40u32 {
app.proc.procs.push(crate::collect::proc::ProcRow {
pid: 1000 + k,
name: format!("proc{k}"),
net_recv: 10,
net_sent: 5,
net_rr: 1.0,
net_sr: 0.5,
udp_recv: 0,
udp_sent: 0,
udp_rr: 0.0,
udp_sr: 0.0,
disk_r: 0,
disk_w: 0,
disk_rr: 0.0,
disk_wr: 0.0,
uptime_s: None, alive: true,
cmdline: None,
});
}
let n = crate::ui::procs_display(&app).len();
for (w, h) in [(249u16, 67u16), (80, 24), (100, 30), (60, 18)] {
for sel in 0..n + 2 {
app.sel[BOX_PROCS] = (sel < n).then_some(sel);
let mut term = Terminal::new(TestBackend::new(w, h)).unwrap();
term.draw(|f| draw(f, &app))
.unwrap_or_else(|e| panic!("{w}x{h} sel {sel}: {e}"));
}
}
}
#[test]
fn detail_popup_renders_exited_process() {
use ratatui::backend::TestBackend;
use ratatui::Terminal;
let mut app = crate::app::App::new(None);
app.update();
let mut row = crate::collect::proc::ProcRow {
pid: 4242,
name: "deadproc".into(),
net_recv: 100,
net_sent: 50,
net_rr: 0.0,
net_sr: 0.0,
udp_recv: 0,
udp_sent: 0,
udp_rr: 0.0,
udp_sr: 0.0,
disk_r: 0,
disk_w: 0,
disk_rr: 0.0,
disk_wr: 0.0,
uptime_s: None, alive: false,
cmdline: Some(vec!["/usr/bin/deadproc".into(), "--flag".into()]),
};
app.proc.procs.push(row.clone());
let buf_text = |term: &Terminal<TestBackend>| {
let buf = term.backend().buffer();
(0..buf.area().height)
.map(|y| {
(0..buf.area().width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect::<String>()
})
.collect::<String>()
};
app.menu = crate::app::MenuState::Detail(BOX_PROCS, 4242);
let mut term = Terminal::new(TestBackend::new(120, 40)).unwrap();
term.draw(|f| draw(f, &app)).unwrap();
let text = buf_text(&term);
assert!(text.contains("exited"), "status shown");
assert!(text.contains("/usr/bin/deadproc"), "captured cmdline shown");
assert!(text.contains("[s] start/restart"), "start hint shown");
row.alive = true;
row.pid = std::process::id();
app.proc.procs.push(row);
app.menu = crate::app::MenuState::Detail(BOX_PROCS, u64::from(std::process::id()));
let mut term = Terminal::new(TestBackend::new(120, 40)).unwrap();
term.draw(|f| draw(f, &app)).unwrap();
let text = buf_text(&term);
assert!(text.contains("running"), "alive row shows running");
assert!(!text.contains("exited"), "no exited banner for a live row");
assert!(text.contains("[s] start/restart"), "resident start hint");
}
#[test]
fn detail_panel_wraps_cmd_and_pins_the_hint_row() {
use ratatui::backend::TestBackend;
use ratatui::Terminal;
let mut app = crate::app::App::new(None);
app.update();
let tail = "and-a-long-tail-marker".to_string();
let long_cmd = format!("/usr/bin/deadproc --very-long-option={} {}", "x".repeat(120), tail);
app.proc.procs.push(crate::collect::proc::ProcRow {
pid: 4242,
name: "deadproc".into(),
net_recv: 100,
net_sent: 50,
net_rr: 0.0,
net_sr: 0.0,
udp_recv: 0,
udp_sent: 0,
udp_rr: 0.0,
udp_sr: 0.0,
disk_r: 0,
disk_w: 0,
disk_rr: 0.0,
disk_wr: 0.0,
uptime_s: None, alive: false,
cmdline: Some(vec![long_cmd]),
});
app.menu = crate::app::MenuState::Detail(BOX_PROCS, 4242);
let buf_text = |term: &Terminal<TestBackend>| {
let buf = term.backend().buffer();
(0..buf.area().height)
.map(|y| {
(0..buf.area().width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect::<String>()
})
.collect::<String>()
};
let mut term = Terminal::new(TestBackend::new(100, 30)).unwrap();
term.draw(|f| draw(f, &app)).unwrap();
let text = buf_text(&term);
assert!(text.contains(&tail), "wrapped cmd tail is rendered");
assert!(text.contains("[esc] close"), "hints complete");
let mut term = Terminal::new(TestBackend::new(60, 10)).unwrap();
term.draw(|f| draw(f, &app)).unwrap();
let text = buf_text(&term);
assert!(text.contains("[esc] close"), "hints pinned to the bottom");
assert!(text.contains("[s] start/restart"), "s hint visible");
assert!(text.contains("[k] kill pid 4242"), "k hint visible");
}
#[test]
fn procs_overlay_follows_the_pinned_order() {
use ratatui::backend::TestBackend;
use ratatui::Terminal;
let mut app = crate::app::App::new(None);
app.update();
for (pid, name) in [(100u32, "aaa"), (200u32, "bbb")] {
app.proc.procs.push(crate::collect::proc::ProcRow {
pid,
name: name.into(),
net_recv: 10,
net_sent: 0,
net_rr: 0.0,
net_sr: 0.0,
udp_recv: 0,
udp_sent: 0,
udp_rr: 0.0,
udp_sr: 0.0,
disk_r: 0,
disk_w: 0,
disk_rr: 0.0,
disk_wr: 0.0,
uptime_s: None, alive: true,
cmdline: None,
});
}
app.tracked.toggle_proc(200); for i in [BOX_LAN, BOX_CONNS, BOX_DISKS] {
app.visible[i] = false;
}
app.focus[BOX_PROCS] = true;
app.sel[BOX_PROCS] = Some(1); let mut term = Terminal::new(TestBackend::new(120, 40)).unwrap();
term.draw(|f| draw(f, &app)).unwrap();
let buf = term.backend().buffer();
let text: String = (0..buf.area().height)
.map(|y| {
(0..buf.area().width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect::<String>()
})
.collect();
assert!(text.contains("(pid 100"), "overlay shows the selected row's process");
assert!(!text.contains("(pid 200"), "overlay must not show the pre-pin occupant");
}
#[test]
fn selection_follows_the_entity_through_resorts() {
let mut app = crate::app::App::new(None);
app.update();
for (pid, name, recv) in [(100u32, "aaa", 10u64), (200u32, "bbb", 1000u64)] {
app.proc.procs.push(crate::collect::proc::ProcRow {
pid,
name: name.into(),
net_recv: recv,
net_sent: 0,
net_rr: 0.0,
net_sr: 0.0,
udp_recv: 0,
udp_sent: 0,
udp_rr: 0.0,
udp_sr: 0.0,
disk_r: 0,
disk_w: 0,
disk_rr: 0.0,
disk_wr: 0.0,
uptime_s: None, alive: true,
cmdline: None,
});
}
app.sel[BOX_PROCS] = Some(0); let anchor = selected_id(&app, BOX_PROCS);
assert_eq!(anchor, Some(100));
app.proc.procs.swap(0, 1);
reselect(&mut app, BOX_PROCS, anchor.unwrap());
assert_eq!(app.sel[BOX_PROCS], Some(1));
app.proc.procs.retain(|p| p.pid != 100);
reselect(&mut app, BOX_PROCS, anchor.unwrap());
assert_eq!(app.sel[BOX_PROCS], None);
let mk = |inode: u64| crate::collect::conn::Conn {
proto: 6,
local: ("127.0.0.1".parse().unwrap(), 1000 + inode as u16),
remote: ("127.0.0.1".parse().unwrap(), 80),
state: 1,
uid: 0,
inode,
bytes_recv: 0,
bytes_sent: 0,
rate_recv: 0.0,
rate_sent: 0.0,
pid: None,
proc: None,
dead: false,
first_seen: None,
dead_at: None,
};
app.conn.sort = crate::collect::conn::ConnSort::Name; app.conn.conns = vec![mk(11), mk(22)];
app.sel[BOX_CONNS] = Some(1); let anchor = selected_id(&app, BOX_CONNS);
assert_eq!(anchor, Some(22));
app.conn.conns.swap(0, 1); reselect(&mut app, BOX_CONNS, anchor.unwrap());
assert_eq!(app.sel[BOX_CONNS], Some(0), "selection follows the inode");
}
#[test]
fn conns_bottom_scroll_shows_full_last_page() {
use ratatui::backend::TestBackend;
use ratatui::Terminal;
let mut app = crate::app::App::new(None);
for i in 0..BOX_COUNT {
app.visible[i] = i == BOX_CONNS;
}
let n = 200usize;
for k in 0..n {
app.conn.conns.push(crate::collect::conn::Conn {
proto: crate::collect::conn::IPPROTO_TCP,
local: ("127.0.0.1".parse().unwrap(), 1000 + k as u16),
remote: ("127.0.0.1".parse().unwrap(), 443),
state: 1,
uid: 0,
inode: k as u64,
bytes_recv: 0,
bytes_sent: 0,
rate_recv: 0.0,
rate_sent: 0.0,
pid: Some(1),
proc: Some(format!("c{k:04}")),
dead: false,
first_seen: None,
dead_at: None,
});
}
app.scroll[BOX_CONNS] = 5000;
let mut term = Terminal::new(TestBackend::new(120, 40)).unwrap();
term.draw(|f| draw(f, &app)).unwrap();
let buf = term.backend().buffer();
let rows: Vec<String> = (0..buf.area.height)
.map(|y| {
(0..buf.area.width)
.map(|x| buf[(x, y)].symbol())
.collect()
})
.collect();
let shown: Vec<&String> = rows.iter().filter(|r| r.contains("c019")).collect();
assert!(!shown.is_empty(), "最后一页应包含尾段连接");
assert!(shown.len() >= 5, "尾页行数 {} < 5,像是只剩单行", shown.len());
assert!(!rows.iter().any(|r| r.contains("c0000")), "越界滚动后仍显示首行");
}
#[test]
fn aggregate_selection_shows_group_summary() {
use ratatui::backend::TestBackend;
use ratatui::Terminal;
let mut app = crate::app::App::new(None);
for i in [BOX_NET, BOX_DISKIO, BOX_DISKS, BOX_LAN, BOX_PROCS] {
app.visible[i] = false;
}
let mk = |inode: u64, recv: u64| crate::collect::conn::Conn {
proto: crate::collect::conn::IPPROTO_TCP,
local: ("127.0.0.1".parse().unwrap(), 1000 + inode as u16),
remote: ("127.0.0.1".parse().unwrap(), 443),
state: 1,
uid: 0,
inode,
bytes_recv: recv,
bytes_sent: 0,
rate_recv: 0.0,
rate_sent: 0.0,
pid: Some(1000 + inode as u32),
proc: Some("firefox".into()),
dead: false,
first_seen: None,
dead_at: None,
};
app.conn.conns = vec![mk(1, 100), mk(2, 900), mk(3, 50)];
app.conn.sort = crate::collect::conn::ConnSort::Proc;
app.sel[BOX_CONNS] = Some(0); app.focus[BOX_CONNS] = true;
fn rows_containing(buf: &str, needle: &str, cap: usize) -> bool {
buf.matches(needle).count() >= cap
}
let mut term = Terminal::new(TestBackend::new(120, 16)).unwrap();
term.draw(|f| draw(f, &app)).unwrap();
let buf: String = term
.backend()
.buffer()
.content
.iter()
.map(|c| c.symbol())
.collect();
assert!(buf.contains("firefox ×3"), "组摘要缺失");
assert!(buf.contains("1.0KiB"), "组 Σ 缺失");
assert!(!rows_containing(&buf, "127.0.0.1:1001", 3), "成员 IP 不应出现在摘要里");
}
#[test]
fn proc_sort_groups_same_name_with_marker() {
use ratatui::backend::TestBackend;
use ratatui::Terminal;
let mut app = crate::app::App::new(None);
for i in [BOX_NET, BOX_DISKIO, BOX_DISKS, BOX_LAN, BOX_PROCS] {
app.visible[i] = false;
}
let mk = |inode: u64, recv: u64| crate::collect::conn::Conn {
proto: crate::collect::conn::IPPROTO_TCP,
local: ("127.0.0.1".parse().unwrap(), 1000 + inode as u16),
remote: ("127.0.0.1".parse().unwrap(), 443),
state: 1,
uid: 0,
inode,
bytes_recv: recv,
bytes_sent: 0,
rate_recv: 0.0,
rate_sent: 0.0,
pid: Some(1000 + inode as u32),
proc: Some("firefox".into()),
dead: false,
first_seen: None,
dead_at: None,
};
app.conn.conns = vec![mk(1, 100), mk(2, 900), mk(3, 50)];
app.conn.sort = crate::collect::conn::ConnSort::Proc;
let mut term = Terminal::new(TestBackend::new(120, 16)).unwrap();
term.draw(|f| draw(f, &app)).unwrap();
let buf: String = term
.backend()
.buffer()
.content
.iter()
.map(|c| c.symbol())
.collect();
eprintln!("BUF:\n{}", {
let b = term.backend().buffer();
(0..b.area.height)
.map(|y| (0..b.area.width).map(|x| b[(x, y)].symbol()).collect::<String>())
.collect::<Vec<_>>()
.join("\n")
});
assert!(buf.contains("firefox ×3"), "组首 ×N 标识缺失");
assert!(buf.contains("1.0KiB"), "聚合 Σ 缺失");
assert!(!buf.contains("900B"), "折叠时子行不应显示");
app.expanded.insert("firefox".into());
term.draw(|f| draw(f, &app)).unwrap();
let buf: String = term
.backend()
.buffer()
.content
.iter()
.map(|c| c.symbol())
.collect();
assert!(buf.contains("900B") && buf.contains("100B") && buf.contains("50B"), "展开后子行缺失");
assert!(buf.contains("c"), "应有连接行");
}
#[test]
fn classic_right_column_snaps_to_midline() {
use ratatui::backend::TestBackend;
use ratatui::Terminal;
let mut app = crate::app::App::new(None);
app.layout = crate::app::LayoutMode::Classic;
for i in 0..BOX_COUNT {
app.visible[i] = true;
}
for k in 0..5u32 {
app.lan.neighbors.insert(
format!("10.0.0.{}", k + 1).parse().unwrap(),
crate::collect::lan::Neighbor {
ip: format!("10.0.0.{}", k + 1).parse().unwrap(),
mac: None,
iface: "eth0".into(),
complete: true,
hostname: None,
is_gateway: false,
is_self: false,
last_seen: std::time::Instant::now(),
},
);
}
let mut term = Terminal::new(TestBackend::new(140, 40)).unwrap();
term.draw(|f| draw(f, &app)).unwrap();
let buf = term.backend().buffer();
let rows: Vec<String> = (0..buf.area.height)
.map(|y| {
(0..buf.area.width)
.map(|x| buf[(x, y)].symbol())
.collect()
})
.collect();
let title_row = |tag: &str| -> usize {
rows.iter()
.enumerate()
.find(|(_, r)| r.contains(tag))
.map(|(y, _)| y)
.unwrap_or_else(|| panic!("找不到标题 {tag}"))
};
let _y_net = title_row("\u{b9}net"); let y_diskio = title_row("\u{b3}disk i/o"); let y_lan = title_row("\u{b2}lan"); let y_conns = title_row("\u{2075}conns"); let y_procs = title_row("\u{2076}procs"); let net_bottom = y_diskio - 1; let conns_bottom = y_procs - 1;
assert_eq!(
conns_bottom, net_bottom,
"CONNS 底边框(行 {conns_bottom})未对齐 NET 底边框(行 {net_bottom})"
);
assert!(y_conns - 1 > y_lan + 1, "LAN 与 CONNS 应相邻且 LAN 有内容区");
assert!(rows.iter().any(|r| r.contains("10.0.0.3")), "第 3 台设备应可见");
assert!(!rows.iter().any(|r| r.contains("10.0.0.4")), "第 4 台设备应被滚动窗口裁掉");
}
#[test]
fn search_filters_procs_and_conns_by_name() {
use crate::collect::conn::IPPROTO_TCP;
let mut app = crate::app::App::new(None);
app.proc.procs.push(crate::collect::proc::ProcRow {
pid: 1,
name: "firefox".into(),
net_recv: 10,
net_sent: 5,
net_rr: 0.0,
net_sr: 0.0,
udp_recv: 0,
udp_sent: 0,
udp_rr: 0.0,
udp_sr: 0.0,
disk_r: 0,
disk_w: 0,
disk_rr: 0.0,
disk_wr: 0.0,
uptime_s: None, alive: true,
cmdline: None,
});
app.proc.procs.push(crate::collect::proc::ProcRow {
pid: 2,
name: "chrome".into(),
..app.proc.procs[0].clone()
});
app.conn.conns.push(crate::collect::conn::Conn {
proto: IPPROTO_TCP,
local: ("127.0.0.1".parse().unwrap(), 1000),
remote: ("127.0.0.1".parse().unwrap(), 443),
state: 1,
uid: 0,
inode: 9,
bytes_recv: 0,
bytes_sent: 0,
rate_recv: 0.0,
rate_sent: 0.0,
pid: Some(1),
proc: Some("firefox".into()),
dead: false,
first_seen: None,
dead_at: None,
});
app.search = "FIRE".into(); app.search_box = BOX_CONNS; let names: Vec<_> = procs_display(&app).iter().map(|p| p.name.clone()).collect();
assert_eq!(names.len(), 2, "目标 conns 时 procs 不过滤");
let conns = conns_display(&app);
assert_eq!(conns.len(), 1, "目标 conns 应过滤连接归属");
app.search_box = BOX_PROCS;
let names: Vec<_> = procs_display(&app).iter().map(|p| p.name.clone()).collect();
assert_eq!(names, vec!["firefox"], "目标 procs 应过滤进程");
assert_eq!(conns_display(&app).len(), 1, "非目标盒 conns 应直通不清空");
app.search.clear();
assert_eq!(procs_display(&app).len(), 2, "清空搜索应恢复全部");
}
#[test]
fn conn_filter_cycles_all_lan_tcp_udp() {
use crate::collect::conn::{ConnFilter, IPPROTO_TCP, IPPROTO_UDP};
let mut app = crate::app::App::new(None);
let mk = |inode: u64, proto: u8, remote: std::net::IpAddr| {
crate::collect::conn::Conn {
proto,
local: ("127.0.0.1".parse().unwrap(), 1000 + inode as u16),
remote: (remote, 443),
state: 1,
uid: 0,
inode,
bytes_recv: 0,
bytes_sent: 0,
rate_recv: 0.0,
rate_sent: 0.0,
pid: None,
proc: None,
dead: false,
first_seen: None,
dead_at: None,
}
};
let lan = std::net::IpAddr::V4("192.168.1.9".parse().unwrap());
app.conn.conns = vec![
mk(1, IPPROTO_TCP, "93.184.216.34".parse().unwrap()), mk(2, IPPROTO_TCP, lan), mk(3, IPPROTO_UDP, lan), ];
app.conn.filter = ConnFilter::All;
assert_eq!(conns_display(&app).len(), 3);
app.conn.filter = ConnFilter::Lan;
assert_eq!(conns_display(&app).len(), 2, "lan 应滤掉外网");
app.conn.filter = ConnFilter::Tcp;
assert_eq!(conns_display(&app).len(), 2, "tcp 应只剩两条 tcp");
assert!(conns_display(&app).iter().all(|c| c.is_tcp()));
app.conn.filter = ConnFilter::Udp;
assert_eq!(conns_display(&app).len(), 1, "udp 应只剩一条 udp");
assert_eq!(ConnFilter::Udp.next(), ConnFilter::All);
}
#[test]
fn lan_list_scrolls_with_offset() {
use ratatui::backend::TestBackend;
use ratatui::Terminal;
let mut app = crate::app::App::new(None);
for i in 0..BOX_COUNT {
app.visible[i] = i == BOX_LAN;
}
for k in 0..30u32 {
app.lan.neighbors.insert(
format!("10.0.0.{}", k + 1).parse().unwrap(),
crate::collect::lan::Neighbor {
ip: format!("10.0.0.{}", k + 1).parse().unwrap(),
mac: None,
iface: "eth0".into(),
complete: true,
hostname: None,
is_gateway: false,
is_self: false,
last_seen: std::time::Instant::now(),
},
);
}
let render_buf = |app: &crate::app::App| {
let mut term = Terminal::new(TestBackend::new(120, 16)).unwrap();
term.draw(|f| draw(f, app)).unwrap();
term.backend()
.buffer()
.content
.iter()
.map(|c| c.symbol())
.collect::<String>()
};
let render_first_ip = |app: &crate::app::App| {
let mut term = Terminal::new(TestBackend::new(120, 16)).unwrap();
term.draw(|f| draw(f, app)).unwrap();
let buf: String = term
.backend()
.buffer()
.content
.iter()
.map(|c| c.symbol())
.collect();
(0..30u32)
.filter(|k| buf.contains(&format!("10.0.0.{} ", k + 1)))
.collect::<Vec<_>>()
};
app.scroll[BOX_LAN] = 0;
let at0 = render_first_ip(&app);
assert!(at0.contains(&0), "首屏应含第 1 台");
assert!(!at0.contains(&20), "首屏不应含第 21 台");
assert!(at0.contains(&0), "占位");
let buf0 = render_buf(&app);
assert!(buf0.contains("+18"), "+N 提示缺失或错误");
app.scroll[BOX_LAN] = 20;
let at20 = render_first_ip(&app);
assert!(at20.contains(&20), "滚动后应见第 21 台");
assert!(!at20.contains(&0), "滚动后首屏不应再含第 1 台");
}
#[test]
fn conn_rows_carry_protocol_labels_without_glyphs() {
use ratatui::backend::TestBackend;
use ratatui::Terminal;
let mut app = crate::app::App::new(None);
app.conn.filter = crate::collect::conn::ConnFilter::All;
for i in [BOX_NET, BOX_DISKIO, BOX_DISKS, BOX_LAN] {
app.visible[i] = false;
}
let mk = |inode: u64, name: &str, proto: u8, state: u8| {
crate::collect::conn::Conn {
proto,
local: ("127.0.0.1".parse().unwrap(), 1000 + inode as u16),
remote: ("127.0.0.1".parse().unwrap(), 443),
state,
uid: 0,
inode,
bytes_recv: 0,
bytes_sent: 0,
rate_recv: 0.0,
rate_sent: 0.0,
pid: Some(7),
proc: Some(name.to_string()),
dead: false,
first_seen: None,
dead_at: None,
}
};
app.conn.conns = vec![
mk(1, "demo", crate::collect::conn::IPPROTO_TCP, crate::collect::conn::TCP_ESTABLISHED),
mk(2, "demo2", crate::collect::conn::IPPROTO_UDP, 7),
mk(3, "demo3", crate::collect::conn::IPPROTO_TCP, crate::collect::conn::TCP_LISTEN),
];
let mut term = Terminal::new(TestBackend::new(160, 30)).unwrap();
app.conn.sort = crate::collect::conn::ConnSort::Rate;
term.draw(|f| draw(f, &app)).unwrap();
let buf: String = term
.backend()
.buffer()
.content
.iter()
.map(|c| c.symbol())
.collect();
assert!(buf.contains("RX/S"), "rate 表头缺失");
assert!(!buf.contains("Σ RX"), "rate 模式不应出现 Σ 表头");
app.conn.sort = crate::collect::conn::ConnSort::Sum;
term.draw(|f| draw(f, &app)).unwrap();
let buf: String = term
.backend()
.buffer()
.content
.iter()
.map(|c| c.symbol())
.collect();
assert!(buf.contains("Σ RX") && buf.contains("Σ TX"), "sum 表头缺失");
assert!(!buf.contains("RX/S"), "sum 模式不应残留速率表头");
app.conn.sort = crate::collect::conn::ConnSort::Proc;
term.draw(|f| draw(f, &app)).unwrap();
let buf: String = term
.backend()
.buffer()
.content
.iter()
.map(|c| c.symbol())
.collect();
assert!(buf.contains("Σ RX"), "proc 档应显示合计表头");
eprintln!("DEMO-HITS: {}", ["demo tcp","demo2 udp","◦demo3 tcp","demo","demo2","demo3"].iter().map(|t| format!("{t}={}", buf.contains(t))).collect::<Vec<_>>().join(" "));
eprintln!("FULL: {}", buf.replace("\n", "|"));
assert!(buf.contains("demo tcp"), "tcp 标签缺失");
assert!(buf.contains("demo2 udp"), "udp 标签缺失");
assert!(buf.contains("demo3 \u{25e6}tcp"), "监听标签缺失");
for gone in ["\u{25b8}", "\u{22c4}"] {
assert!(!buf.contains(gone), "旧符号 {gone} 仍在");
}
}
#[test]
fn layout_priority_favours_lists() {
assert_eq!(split_horizontal(150, 76, 40), (74, 76));
assert_eq!(split_horizontal(100, 76, 40), (40, 60)); assert_eq!(split_horizontal(60, 76, 40), (30, 30)); assert_eq!(split_vertical(100, 4, 30), (50, 50));
assert_eq!(split_vertical(40, 4, 30), (10, 30));
assert_eq!(split_vertical(20, 8, 30), (8, 12));
assert_eq!(split_vertical(12, 8, 30), (8, 4));
}
#[test]
fn tall_layout_caps_graphs_at_half_height() {
use ratatui::backend::TestBackend;
use ratatui::Terminal;
let mut app = crate::app::App::new(None);
app.layout = crate::app::LayoutMode::Tall;
for i in [BOX_LAN, BOX_CONNS, BOX_DISKS] {
app.visible[i] = false;
}
app.update();
let mut term = Terminal::new(TestBackend::new(200, 60)).unwrap();
term.draw(|f| crate::ui::draw(f, &app)).unwrap();
let buf = term.backend().buffer();
let rows: Vec<String> = (0..buf.area().height)
.map(|y| {
(0..buf.area().width)
.map(|x| buf[(x, y)].symbol().to_string())
.collect()
})
.collect();
let title_row = |tag: &str| {
rows.iter()
.position(|r| r.contains(tag))
.unwrap_or_else(|| panic!("找不到标题 {tag}"))
};
let y_net = title_row("\u{b9}net"); let y_procs = title_row("\u{2076}procs"); assert!(
y_procs - y_net <= 32,
"图表区应 ≤ 半屏:net@{y_net} procs@{y_procs}(总高 60)"
);
}
#[test]
fn stable_alloc_ignores_blips_and_adopts_real_changes() {
use std::time::{Duration, Instant};
let t0 = Instant::now();
let mut m = StableAlloc::new();
assert_eq!(m.update(vec![10, 20], 30, t0), vec![10, 20]);
assert_eq!(
m.update(vec![12, 18], 30, t0 + Duration::from_secs(5)),
vec![10, 20]
);
assert_eq!(
m.update(vec![14, 16], 30, t0 + Duration::from_secs(10)),
vec![14, 16]
);
assert_eq!(
m.update(vec![20, 30], 50, t0 + Duration::from_secs(10)),
vec![20, 30]
);
assert_eq!(
m.update(vec![20, 40], 50, t0 + Duration::from_secs(20)),
vec![20, 30]
);
}
#[test]
fn alloc_heights_gives_spare_to_priority_boxes() {
assert_eq!(
alloc_heights(&[6, 12, 4, 10], 40, &[1, 2]),
vec![6, 16, 8, 10]
);
assert_eq!(
alloc_heights(&[6, 12, 4, 10], 39, &[1, 2]),
vec![6, 16, 7, 10]
);
assert_eq!(alloc_heights(&[6, 8, 4, 5], 40, &[]), vec![11, 12, 8, 9]);
}
#[test]
fn alloc_heights_shrinks_proportionally_when_cramped() {
assert_eq!(alloc_heights(&[10, 10], 10, &[]), vec![5, 5]);
assert_eq!(alloc_heights(&[10, 10], 6, &[1]), vec![3, 3]);
assert!(alloc_heights(&[8, 8, 8], 5, &[]).iter().all(|&h| h >= 1));
}
}