use crate::model::{gpu::GpuSnapshot, memory::MemorySnapshot};
use ratatui::{
prelude::*,
widgets::{Block, Borders, Paragraph, Wrap},
};
pub fn render(frame: &mut Frame<'_>, area: Rect, memory: &MemorySnapshot) {
let block = Block::default().title(" MEMORY ").borders(Borders::ALL);
let width = block.inner(area).width.saturating_sub(1) as usize;
let text = format!(
"RAM {}\nSWAP {}",
bar(memory.ram_used_bytes, memory.ram_total_bytes, width),
bar(memory.swap_used_bytes, memory.swap_total_bytes, width)
);
frame.render_widget(
Paragraph::new(text).block(block).wrap(Wrap { trim: true }),
area,
);
}
pub fn vram_line(gpu: &GpuSnapshot, width: usize) -> String {
format!(
"VRAM {}",
bar(
gpu.used_memory_bytes.unwrap_or_default(),
gpu.total_memory_bytes.unwrap_or_default(),
width,
)
)
}
fn bar(used: u64, total: u64, width: usize) -> String {
let cells = width.saturating_sub(18).max(4);
let filled = if total == 0 {
0
} else {
((used as f64 / total as f64).clamp(0.0, 1.0) * cells as f64).round() as usize
};
format!(
"[{}{}] {} / {}",
"█".repeat(filled),
"░".repeat(cells.saturating_sub(filled)),
bytes(used),
bytes(total)
)
}
fn bytes(value: u64) -> String {
if value >= 1 << 30 {
format!("{:.1}G", value as f64 / (1 << 30) as f64)
} else {
format!("{:.0}M", value as f64 / (1 << 20) as f64)
}
}