use crate::display::common::tui::ScrollState;
use comfy_table::{Attribute, Cell, CellAlignment, Color, Table, presets::UTF8_FULL};
use ratatui::{
Frame,
layout::{Alignment, Constraint, Direction, Layout, Margin, Rect},
style::{Color as RatatuiColor, Modifier, Style, Stylize},
text::{Line, Span, Text},
widgets::{
Block, Borders, Cell as RatatuiCell, Paragraph, Row as RatatuiRow, Scrollbar,
ScrollbarOrientation, ScrollbarState, Table as RatatuiTable,
},
};
use sysinfo::System;
fn normalized_cpu(raw: f32, cores: f32) -> f32 {
(raw / cores).clamp(0.0, 100.0)
}
pub fn refresh_process_metrics(sys: &mut System, pid: sysinfo::Pid) {
sys.refresh_processes_specifics(
sysinfo::ProcessesToUpdate::Some(&[pid]),
true,
sysinfo::ProcessRefreshKind::nothing()
.with_cpu()
.with_memory(),
);
}
pub fn init_process_metrics(sys: &mut System, pid: sysinfo::Pid) {
sys.refresh_cpu_all();
refresh_process_metrics(sys, pid);
}
pub fn create_title(title_text: &str, color: RatatuiColor) -> Paragraph<'_> {
Paragraph::new(vec![Line::from(vec![Span::styled(
title_text,
Style::default().fg(color).bold(),
)])])
.block(
Block::default()
.borders(Borders::ALL)
.border_style(Style::default().fg(color)),
)
.centered()
}
const SUMMARY_SEP: &str = " | ";
fn seg_width(s: &str) -> usize {
s.chars().count()
}
fn fit_diagnostics(
used: usize,
available: usize,
mem_width: usize,
cpu_width: usize,
) -> (bool, bool) {
if used + mem_width > available {
return (false, false);
}
(true, used + mem_width + cpu_width <= available)
}
pub fn create_summary<'a>(
summary_items: Vec<(&'a str, &'a str, RatatuiColor)>, sys: &'a System,
pid: sysinfo::Pid,
width: u16,
) -> Paragraph<'a> {
let available = width.saturating_sub(2) as usize;
let mut spans = Vec::new();
let mut used = 0usize;
for (i, (icon, value, color)) in summary_items.iter().enumerate() {
if i > 0 {
spans.push(Span::raw(SUMMARY_SEP));
used += seg_width(SUMMARY_SEP);
}
let label = format!("{} ", icon);
used += seg_width(&label) + seg_width(value);
spans.push(Span::styled(label, Style::default().fg(*color).bold()));
spans.push(Span::styled(*value, Style::default().fg(*color).bold()));
}
let memory_mb = sys
.process(pid)
.map_or(0.0, |p| p.memory() as f64 / 1024.0 / 1024.0);
let mem_value = format!("{:.1} MB", memory_mb);
let mem_width = seg_width(SUMMARY_SEP) + seg_width("Memory: ") + seg_width(&mem_value);
let cores = sys.cpus().len().max(1) as f32;
let cpu_percent = sys
.process(pid)
.map_or(0.0, |p| normalized_cpu(p.cpu_usage(), cores));
let cpu_value = format!("{:.1}%", cpu_percent);
let cpu_width = seg_width(SUMMARY_SEP) + seg_width("CPU: ") + seg_width(&cpu_value);
let (show_mem, show_cpu) = fit_diagnostics(used, available, mem_width, cpu_width);
if show_mem {
spans.push(Span::raw(SUMMARY_SEP));
spans.push(Span::styled(
"Memory: ",
Style::default().fg(RatatuiColor::LightRed).bold(),
));
spans.push(Span::styled(
mem_value,
Style::default().fg(RatatuiColor::LightYellow).bold(),
));
}
if show_cpu {
spans.push(Span::raw(SUMMARY_SEP));
spans.push(Span::styled(
"CPU: ",
Style::default().fg(RatatuiColor::LightRed).bold(),
));
spans.push(Span::styled(
cpu_value,
Style::default().fg(RatatuiColor::LightYellow).bold(),
));
}
Paragraph::new(vec![Line::from(spans)])
.block(
Block::default()
.borders(Borders::ALL)
.border_style(Style::default().fg(RatatuiColor::Yellow)),
)
.centered()
}
pub const REPO_LABEL: &str = "Star on GitHub";
pub const REPO_URL: &str = "https://github.com/Mai0313/VibeCodingTracker";
pub fn create_controls(extra: &[(&str, &str)]) -> Paragraph<'static> {
create_controls_with_status(extra, None)
}
pub fn create_controls_with_status(
extra: &[(&str, &str)],
status: Option<&str>,
) -> Paragraph<'static> {
let key = Style::default().fg(RatatuiColor::Cyan).bold();
let dim = Style::default().fg(RatatuiColor::DarkGray);
let mut spans = vec![Span::styled("↑/↓", key), Span::styled(" scroll ", dim)];
for (k, label) in extra {
spans.push(Span::styled(k.to_string(), key));
spans.push(Span::styled(label.to_string(), dim));
}
spans.push(Span::styled("r", key));
spans.push(Span::styled(" refresh ", dim));
spans.push(Span::styled(
"q",
Style::default().fg(RatatuiColor::Red).bold(),
));
spans.push(Span::styled(" quit", dim));
if let Some(status) = status {
spans.push(Span::styled(" | ", dim));
spans.push(Span::styled(
status.to_string(),
Style::default().fg(RatatuiColor::Yellow).bold(),
));
}
spans.push(Span::styled(" | ", dim));
spans.push(Span::styled(
REPO_LABEL,
Style::default().fg(RatatuiColor::Cyan).underlined(),
));
Paragraph::new(vec![Line::from(spans)]).centered()
}
pub struct FrameChunks {
pub table: Rect,
pub panels: Option<Rect>,
pub summary: Rect,
pub controls: Rect,
}
pub fn main_layout(area: Rect, panels_height: Option<u16>) -> FrameChunks {
match panels_height {
Some(h) => {
let c = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Min(6),
Constraint::Length(h),
Constraint::Length(3),
Constraint::Length(1),
])
.split(area);
FrameChunks {
table: c[0],
panels: Some(c[1]),
summary: c[2],
controls: c[3],
}
}
None => {
let c = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Min(6),
Constraint::Length(3),
Constraint::Length(1),
])
.split(area);
FrameChunks {
table: c[0],
panels: None,
summary: c[1],
controls: c[2],
}
}
}
}
pub fn styled_row(cells: Vec<String>, style: Style, left_cols: usize) -> RatatuiRow<'static> {
let cells: Vec<RatatuiCell> = cells
.into_iter()
.enumerate()
.map(|(i, s)| {
let align = if i < left_cols {
Alignment::Left
} else {
Alignment::Right
};
RatatuiCell::from(Text::from(s).alignment(align))
})
.collect();
RatatuiRow::new(cells).style(style)
}
#[allow(clippy::too_many_arguments)]
pub fn render_scrollable_table(
f: &mut Frame,
area: Rect,
header: Vec<&str>,
rows: Vec<RatatuiRow>,
widths: &[Constraint],
border_color: RatatuiColor,
row_count: usize,
scroll: &mut ScrollState,
) {
let viewport = area.height.saturating_sub(4);
let table = create_ratatui_table(rows, header, widths, border_color).row_highlight_style(
Style::default()
.fg(RatatuiColor::Black)
.bg(RatatuiColor::Cyan)
.add_modifier(Modifier::BOLD),
);
f.render_stateful_widget(table, area, &mut scroll.table);
let selected = scroll.table.selected().unwrap_or(0);
scroll.scrollbar = ScrollbarState::new(row_count)
.viewport_content_length(viewport as usize)
.position(selected);
f.render_stateful_widget(
Scrollbar::new(ScrollbarOrientation::VerticalRight)
.begin_symbol(None)
.end_symbol(None),
area.inner(Margin {
vertical: 1,
horizontal: 0,
}),
&mut scroll.scrollbar,
);
}
pub fn render_too_small(f: &mut Frame, min_w: u16, min_h: u16) {
let area = f.area();
let para = Paragraph::new(vec![
Line::from(Span::styled(
"Terminal too small",
Style::default().fg(RatatuiColor::Red).bold(),
)),
Line::from(Span::styled(
format!(
"resize to at least {min_w} x {min_h} (now {} x {})",
area.width, area.height
),
Style::default().fg(RatatuiColor::Gray),
)),
])
.block(
Block::default()
.borders(Borders::ALL)
.border_style(Style::default().fg(RatatuiColor::Red)),
)
.alignment(Alignment::Center);
let v = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Min(0),
Constraint::Length(4),
Constraint::Min(0),
])
.split(area);
f.render_widget(para, v[1]);
}
pub fn create_ratatui_table<'a>(
rows: Vec<RatatuiRow<'a>>,
header: Vec<&'a str>,
widths: &'a [Constraint],
border_color: RatatuiColor,
) -> RatatuiTable<'a> {
RatatuiTable::new(rows, widths)
.header(
RatatuiRow::new(header)
.style(
Style::default()
.fg(RatatuiColor::Black)
.bg(RatatuiColor::Green)
.bold(),
)
.bottom_margin(1),
)
.block(
Block::default()
.borders(Borders::ALL)
.border_style(Style::default().fg(border_color)),
)
}
pub fn create_comfy_table(headers: Vec<&str>, header_color: Color) -> Table {
let mut table = Table::new();
table.load_preset(UTF8_FULL).set_header(
headers
.iter()
.enumerate()
.map(|(i, &header)| {
let alignment = if i <= 1 {
CellAlignment::Left
} else {
CellAlignment::Right
};
Cell::new(header).fg(header_color).set_alignment(alignment)
})
.collect::<Vec<_>>(),
);
table
}
pub fn add_totals_row(table: &mut Table, cells: Vec<String>, color: Color) {
let colored_cells: Vec<Cell> = cells
.into_iter()
.enumerate()
.map(|(i, text)| {
let alignment = if i <= 1 {
CellAlignment::Left
} else {
CellAlignment::Right
};
Cell::new(text).fg(color).set_alignment(alignment)
})
.collect();
table.add_row(colored_cells);
}
pub fn create_provider_cell(name: String, color: Color, emphasize: bool) -> Cell {
let mut cell = Cell::new(name).fg(color).set_alignment(CellAlignment::Left);
if emphasize {
cell = cell.add_attribute(Attribute::Bold);
}
cell
}
pub fn create_metric_cell(value: String, color: Color, emphasize: bool) -> Cell {
let mut cell = Cell::new(value)
.fg(color)
.set_alignment(CellAlignment::Right);
if emphasize {
cell = cell.add_attribute(Attribute::Bold);
}
cell
}
pub fn create_provider_row<'a>(
cells: Vec<String>,
color: RatatuiColor,
emphasize: bool,
) -> RatatuiRow<'a> {
let style = if emphasize {
Style::default().fg(color).add_modifier(Modifier::BOLD)
} else {
Style::default().fg(color)
};
RatatuiRow::new(cells).style(style)
}
#[cfg(test)]
mod tests {
use super::{fit_diagnostics, normalized_cpu};
#[test]
fn normalized_cpu_divides_by_cores_and_clamps() {
assert!((normalized_cpu(200.0, 4.0) - 50.0).abs() < f32::EPSILON);
assert_eq!(normalized_cpu(0.0, 8.0), 0.0);
assert_eq!(normalized_cpu(410.0, 4.0), 100.0);
}
#[test]
fn fit_diagnostics_drops_cpu_before_memory() {
let (mem, cpu) = (20usize, 15usize); let used = 56;
assert_eq!(fit_diagnostics(used, 91, mem, cpu), (true, true));
assert_eq!(fit_diagnostics(used, used + mem, mem, cpu), (true, false));
assert_eq!(fit_diagnostics(used, 78, mem, cpu), (true, false));
assert_eq!(
fit_diagnostics(used, used + mem - 1, mem, cpu),
(false, false)
);
assert_eq!(fit_diagnostics(used, 60, mem, cpu), (false, false));
}
}