#[allow(unused_imports)]
use ratatui::{
layout::{Alignment, Constraint, Direction, Layout, Rect},
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, Gauge, List, ListItem, Paragraph, Row, Sparkline, Table, Tabs},
Frame,
};
use super::agents_view;
use super::app::{
App, TAB_ACCELERATORS, TAB_AGENT, TAB_AGENTS, TAB_CPU, TAB_INFERENCE, TAB_MEMORY, TAB_OVERVIEW,
TAB_PERIPHERALS, TAB_PROCESSES, TAB_PROFILES, TAB_SYSTEM,
};
use super::inference_view;
mod glances_colors {
use ratatui::style::Color;
pub const OK: Color = Color::Green;
pub const CAREFUL: Color = Color::Cyan;
pub const WARNING: Color = Color::Yellow;
pub const CRITICAL: Color = Color::Red;
pub const TITLE: Color = Color::Cyan;
pub const SEPARATOR: Color = Color::DarkGray;
pub const INACTIVE: Color = Color::DarkGray;
pub const CPU_TITLE: Color = Color::Rgb(0, 255, 255);
pub const ACCEL_TITLE: Color = Color::Rgb(57, 255, 20);
pub const MEMORY_TITLE: Color = Color::Rgb(255, 0, 255);
pub const DISK_TITLE: Color = Color::Rgb(255, 165, 0);
pub const NETWORK_TITLE: Color = Color::Rgb(0, 150, 255);
}
fn threshold_color(percent: f32) -> Color {
match percent {
p if p >= 90.0 => glances_colors::CRITICAL,
p if p >= 70.0 => glances_colors::WARNING,
p if p >= 50.0 => glances_colors::CAREFUL,
_ => glances_colors::OK,
}
}
fn cpu_color(percent: f32) -> Color {
match percent {
p if p >= 90.0 => Color::Rgb(255, 60, 60), p if p >= 70.0 => Color::Rgb(255, 255, 0), p if p >= 50.0 => Color::Rgb(0, 200, 200), _ => Color::Rgb(0, 255, 255), }
}
fn accel_color(percent: f32) -> Color {
match percent {
p if p >= 90.0 => Color::Rgb(255, 60, 60), p if p >= 70.0 => Color::Rgb(255, 255, 0), p if p >= 50.0 => Color::Rgb(80, 255, 80), _ => Color::Rgb(57, 255, 20), }
}
fn memory_color(percent: f32) -> Color {
match percent {
p if p >= 90.0 => Color::Rgb(255, 60, 60), p if p >= 70.0 => Color::Rgb(255, 255, 0), p if p >= 50.0 => Color::Rgb(255, 100, 255), _ => Color::Rgb(255, 0, 255), }
}
fn disk_color(percent: f32) -> Color {
match percent {
p if p >= 90.0 => Color::Rgb(255, 60, 60), p if p >= 70.0 => Color::Rgb(255, 255, 0), p if p >= 50.0 => Color::Rgb(255, 200, 50), _ => Color::Rgb(255, 165, 0), }
}
fn network_color(percent: f32) -> Color {
match percent {
p if p >= 90.0 => Color::Rgb(255, 60, 60), p if p >= 70.0 => Color::Rgb(255, 255, 0), p if p >= 50.0 => Color::Rgb(80, 180, 255), _ => Color::Rgb(0, 150, 255), }
}
fn safe_percent(value: f32) -> u16 {
if value.is_nan() || value.is_infinite() || value < 0.0 {
0
} else if value > 100.0 {
100
} else {
value as u16
}
}
fn threads_text(threads: Option<usize>) -> String {
threads.map_or_else(|| "--".to_string(), |t| t.to_string())
}
fn cores_text(cpu: &crate::tui::app::CpuInfo) -> String {
match cpu.cores {
Some(cores) => format!("{cores} cores"),
None => format!("{} threads", threads_text(cpu.threads)),
}
}
fn opt_mhz(freq: Option<u64>, sep: &str) -> String {
match freq {
Some(mhz) => format!("{sep}{mhz} MHz"),
None => String::new(),
}
}
fn opt_celsius(temp: Option<f32>, sep: &str) -> String {
match temp {
Some(c) => format!("{sep}{c:.0}°C"),
None => String::new(),
}
}
fn trend_indicator(current: f32, previous: f32) -> (&'static str, Color) {
let delta = current - previous;
if delta.abs() < 0.5 {
("→", Color::DarkGray)
} else if delta > 0.0 {
("↑", Color::Red)
} else {
("↓", Color::Green)
}
}
fn auto_unit_or_unknown(bytes: Option<u64>) -> String {
match bytes {
Some(b) => auto_unit(b),
None => "--".to_string(),
}
}
fn auto_unit(bytes: u64) -> String {
const KB: u64 = 1024;
const MB: u64 = KB * 1024;
const GB: u64 = MB * 1024;
const TB: u64 = GB * 1024;
match bytes {
b if b >= TB => format!("{:.1}T", b as f64 / TB as f64),
b if b >= GB => format!("{:.1}G", b as f64 / GB as f64),
b if b >= MB => format!("{:.1}M", b as f64 / MB as f64),
b if b >= KB => format!("{:.1}K", b as f64 / KB as f64),
_ => format!("{}B", bytes),
}
}
pub fn draw(f: &mut Frame, app: &App) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3), Constraint::Min(0), Constraint::Length(3), ])
.split(f.area());
draw_tab_bar(f, app, chunks[0]);
match app.selected_tab {
TAB_INFERENCE => draw_inference_tab(f, app, chunks[1]),
TAB_AGENTS => draw_agents_tab(f, app, chunks[1]),
TAB_OVERVIEW => draw_overview_tab(f, app, chunks[1]),
TAB_PROCESSES => draw_processes_tab(f, app, chunks[1]),
TAB_CPU => draw_cpu_tab(f, app, chunks[1]),
TAB_ACCELERATORS => draw_accelerators_tab(f, app, chunks[1]),
TAB_MEMORY => draw_memory_tab(f, app, chunks[1]),
TAB_SYSTEM => draw_system_tab(f, app, chunks[1]),
TAB_PERIPHERALS => draw_peripherals(f, app, chunks[1]),
TAB_PROFILES => draw_profiles_tab(f, app, chunks[1]),
TAB_AGENT => draw_agent(f, app, chunks[1]),
_ => {}
}
draw_tab_footer(f, app, chunks[2]);
use super::app::ViewMode;
match app.view_mode {
ViewMode::Main => {}
ViewMode::ProcessDetail => draw_process_detail_overlay(f, app),
ViewMode::ThemeSelection => draw_theme_picker_overlay(f, app),
}
}
fn draw_tab_bar(f: &mut Frame, app: &App, area: Rect) {
let titles: Vec<Line> = app.tabs.iter().map(|t| Line::from(*t)).collect();
let cpu_pct = app
.cpu_info
.utilization
.map_or_else(|| "--".to_string(), |p| format!("{p:.0}%"));
let mem_pct = disk_percent(app.memory_info.used, app.memory_info.total)
.map_or_else(|| "--".to_string(), |p| format!("{p:.0}%"));
let title_text = format!(
"IronMonitor │ CPU:{} MEM:{} GPU:{} │ {}",
cpu_pct,
mem_pct,
app.accelerators.len(),
app.system_info.hostname,
);
let tabs = Tabs::new(titles)
.block(
Block::default().borders(Borders::ALL).title(Span::styled(
title_text,
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD),
)),
)
.select(app.selected_tab)
.style(Style::default().fg(Color::DarkGray))
.highlight_style(
Style::default()
.add_modifier(Modifier::BOLD | Modifier::REVERSED)
.fg(glances_colors::TITLE),
)
.divider("│");
f.render_widget(tabs, area);
}
fn draw_overview_tab(f: &mut Frame, app: &App, area: Rect) {
let accel_count = app.accelerators.len();
let accel_height: u16 = if accel_count > 0 {
(accel_count * 3) as u16
} else {
0
};
let mut constraints = vec![Constraint::Length(3)]; if accel_height > 0 {
constraints.push(Constraint::Length(accel_height));
}
constraints.push(Constraint::Length(3)); constraints.push(Constraint::Length(3)); constraints.push(Constraint::Length(3)); constraints.push(Constraint::Min(5));
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(constraints)
.split(area);
let mut idx = 0;
draw_cpu_bar(f, app, chunks[idx]);
idx += 1;
if accel_height > 0 {
draw_accelerators(f, app, chunks[idx]);
idx += 1;
}
draw_memory_bar(f, app, chunks[idx]);
idx += 1;
draw_disk_bar(f, app, chunks[idx]);
idx += 1;
draw_network_bar(f, app, chunks[idx]);
idx += 1;
draw_overview_sparklines(f, app, chunks[idx]);
}
fn draw_overview_sparklines(f: &mut Frame, app: &App, area: Rect) {
let spark_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
.split(area);
let cpu_data: Vec<u64> = app.cpu_history.iter().copied().collect();
if !cpu_data.is_empty() {
let sparkline = Sparkline::default()
.block(
Block::default()
.borders(Borders::ALL)
.title("CPU History (60s)"),
)
.data(&cpu_data)
.style(
Style::default().fg(app.cpu_info.utilization.map_or(Color::DarkGray, cpu_color)),
);
f.render_widget(sparkline, spark_chunks[0]);
} else {
let empty = Block::default()
.borders(Borders::ALL)
.title("CPU History (60s)");
f.render_widget(empty, spark_chunks[0]);
}
let mem_data: Vec<u64> = app.memory_history.iter().copied().collect();
let mem_pct = disk_percent(app.memory_info.used, app.memory_info.total).map(|p| p as f32);
if !mem_data.is_empty() {
let sparkline = Sparkline::default()
.block(
Block::default()
.borders(Borders::ALL)
.title("Memory History (60s)"),
)
.data(&mem_data)
.style(Style::default().fg(mem_pct.map_or(Color::DarkGray, memory_color)));
f.render_widget(sparkline, spark_chunks[1]);
} else {
let empty = Block::default()
.borders(Borders::ALL)
.title("Memory History (60s)");
f.render_widget(empty, spark_chunks[1]);
}
}
fn draw_processes_tab(f: &mut Frame, app: &App, area: Rect) {
draw_nvtop_processes(f, app, area);
}
fn draw_cpu_tab(f: &mut Frame, app: &App, area: Rect) {
let core_count = app.cpu_info.per_core_usage.len();
let core_display_height = (core_count.min(32) + 3) as u16;
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3), Constraint::Length(core_display_height.min(area.height.saturating_sub(11))), Constraint::Min(5), ])
.split(area);
draw_cpu_bar(f, app, chunks[0]);
let mut info_lines = vec![Line::from(vec![
Span::styled("Name: ", Style::default().fg(glances_colors::CPU_TITLE)),
Span::raw(&app.cpu_info.name),
Span::raw(match app.cpu_info.cores {
Some(cores) => format!(
" │ {} cores/{} threads{}{}",
cores,
threads_text(app.cpu_info.threads),
opt_mhz(app.cpu_info.frequency, " │ "),
opt_celsius(app.cpu_info.temperature, " │ "),
),
None => format!(
" │ {} threads{}{}",
threads_text(app.cpu_info.threads),
opt_mhz(app.cpu_info.frequency, " │ "),
opt_celsius(app.cpu_info.temperature, " │ "),
),
}),
])];
let per_core_lines: Vec<Line> = app
.cpu_info
.per_core_usage
.iter()
.enumerate()
.take(32)
.map(|(i, &usage)| {
let Some(usage) = usage else {
return Line::from(vec![
Span::styled(format!("C{i:<2} "), Style::default().fg(Color::DarkGray)),
Span::styled("unread".to_string(), Style::default().fg(Color::DarkGray)),
]);
};
let bar_width: usize = 30;
let filled = (usage / 100.0 * bar_width as f32) as usize;
let bar: String = "█".repeat(filled) + &"░".repeat(bar_width.saturating_sub(filled));
Line::from(vec![
Span::styled(
format!("Core {:>2}: ", i),
Style::default().fg(Color::White),
),
Span::styled(bar, Style::default().fg(cpu_color(usage))),
Span::styled(
format!(" {:>5.1}%", usage),
Style::default()
.fg(cpu_color(usage))
.add_modifier(Modifier::BOLD),
),
])
})
.collect();
info_lines.extend(per_core_lines);
let info = Paragraph::new(info_lines)
.block(Block::default().borders(Borders::ALL).title("CPU Details"))
.style(Style::default().fg(Color::White));
f.render_widget(info, chunks[1]);
let cpu_data: Vec<u64> = app.cpu_history.iter().copied().collect();
if !cpu_data.is_empty() {
let sparkline = Sparkline::default()
.block(
Block::default()
.borders(Borders::ALL)
.title("CPU Utilization History (60s)"),
)
.data(&cpu_data)
.style(
Style::default().fg(app.cpu_info.utilization.map_or(Color::DarkGray, cpu_color)),
);
f.render_widget(sparkline, chunks[2]);
}
}
fn draw_accelerators_tab(f: &mut Frame, app: &App, area: Rect) {
if app.accelerators.is_empty() {
let msg = if app.is_loading() {
"Detecting accelerators..."
} else {
"No accelerators detected"
};
let para = Paragraph::new(msg)
.block(Block::default().borders(Borders::ALL).title("Accelerators"))
.alignment(Alignment::Center);
f.render_widget(para, area);
return;
}
let accel_count = app.accelerators.len();
let info_height = (accel_count * 3) as u16;
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(info_height.min(area.height.saturating_sub(8))),
Constraint::Min(5),
])
.split(area);
draw_accelerators(f, app, chunks[0]);
if !app.accelerator_histories.is_empty() {
let spark_constraints: Vec<Constraint> = app
.accelerators
.iter()
.map(|_| Constraint::Ratio(1, accel_count as u32))
.collect();
let spark_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints(spark_constraints)
.split(chunks[1]);
for (idx, accel) in app.accelerators.iter().enumerate() {
if let Some(history) = app.accelerator_histories.get(idx) {
let data: Vec<u64> = history.iter().copied().collect();
if !data.is_empty() {
let title = format!("{} {} History", accel.accel_type, idx);
let sparkline = Sparkline::default()
.block(Block::default().borders(Borders::ALL).title(title))
.data(&data)
.style(
Style::default()
.fg(accel.utilization.map_or(Color::DarkGray, accel_color)),
);
f.render_widget(sparkline, spark_chunks[idx]);
}
}
}
}
}
fn draw_memory_tab(f: &mut Frame, app: &App, area: Rect) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3), Constraint::Length(10), Constraint::Min(5), ])
.split(area);
draw_memory_bar(f, app, chunks[0]);
let used_gb = app
.memory_info
.used
.map(|v| v as f64 / (1024.0 * 1024.0 * 1024.0));
let total_gb = app
.memory_info
.total
.map(|v| v as f64 / (1024.0 * 1024.0 * 1024.0));
let avail_gb = app
.memory_info
.available
.map(|v| v as f64 / (1024.0 * 1024.0 * 1024.0));
let swap_used_gb = app
.memory_info
.swap_used
.map(|v| v as f64 / (1024.0 * 1024.0 * 1024.0));
let swap_total_gb = app
.memory_info
.swap_total
.map(|v| v as f64 / (1024.0 * 1024.0 * 1024.0));
let mem_pct = disk_percent(app.memory_info.used, app.memory_info.total);
let swap_pct = match (swap_used_gb, swap_total_gb) {
(Some(used), Some(total)) if total > 0.0 => Some((used / total) * 100.0),
_ => None,
};
let bar_width: usize = 40;
let ram_filled = (mem_pct.unwrap_or(0.0) / 100.0 * bar_width as f64) as usize;
let ram_bar: String =
"█".repeat(ram_filled) + &"░".repeat(bar_width.saturating_sub(ram_filled));
let swap_filled = (swap_pct.unwrap_or(0.0) / 100.0 * bar_width as f64) as usize;
let swap_bar: String =
"█".repeat(swap_filled) + &"░".repeat(bar_width.saturating_sub(swap_filled));
let info_lines = vec![
Line::from(vec![
Span::styled(
"RAM: ",
Style::default()
.fg(glances_colors::MEMORY_TITLE)
.add_modifier(Modifier::BOLD),
),
Span::styled(
ram_bar,
Style::default().fg(mem_pct.map_or(Color::DarkGray, |p| memory_color(p as f32))),
),
Span::styled(
match mem_pct {
Some(p) => format!(" {p:.1}%"),
None => " --".to_string(),
},
Style::default()
.fg(mem_pct.map_or(Color::DarkGray, |p| memory_color(p as f32)))
.add_modifier(Modifier::BOLD),
),
]),
Line::from(match (total_gb, used_gb, avail_gb) {
(Some(total), Some(used), Some(avail)) => format!(
" Total: {:.2} GB │ Used: {:.2} GB │ Available: {:.2} GB",
total, used, avail
),
_ => " Total: -- GB │ Used: -- GB │ Available: -- GB".to_string(),
}),
Line::from(""),
Line::from(vec![
Span::styled(
"SWAP: ",
Style::default()
.fg(glances_colors::MEMORY_TITLE)
.add_modifier(Modifier::BOLD),
),
Span::styled(
swap_bar,
Style::default().fg(swap_pct.map_or(Color::DarkGray, |p| memory_color(p as f32))),
),
Span::styled(
match swap_pct {
Some(p) => format!(" {p:.1}%"),
None => " -".to_string(),
},
Style::default()
.fg(swap_pct.map_or(Color::DarkGray, |p| memory_color(p as f32)))
.add_modifier(Modifier::BOLD),
),
]),
Line::from(match (swap_total_gb, swap_used_gb) {
(Some(total), Some(used)) => format!(
" Total: {:.2} GB │ Used: {:.2} GB │ Free: {:.2} GB",
total,
used,
total - used
),
_ => " not reported by this platform".to_string(),
}),
];
let info = Paragraph::new(info_lines)
.block(
Block::default()
.borders(Borders::ALL)
.title("Memory Details"),
)
.style(Style::default().fg(Color::White));
f.render_widget(info, chunks[1]);
let mem_data: Vec<u64> = app.memory_history.iter().copied().collect();
if !mem_data.is_empty() {
let sparkline = Sparkline::default()
.block(
Block::default()
.borders(Borders::ALL)
.title("Memory Usage History (60s)"),
)
.data(&mem_data)
.style(
Style::default().fg(mem_pct.map_or(Color::DarkGray, |p| memory_color(p as f32))),
);
f.render_widget(sparkline, chunks[2]);
}
}
fn draw_system_tab(f: &mut Frame, app: &App, area: Rect) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(8), Constraint::Length(3), Constraint::Min(4), Constraint::Length(3), Constraint::Min(4), Constraint::Length(6), ])
.split(area);
let uptime_text = uptime_opt(app.system_info.uptime);
let mut sys_lines = vec![
Line::from(vec![
Span::styled("Hostname: ", Style::default().fg(glances_colors::TITLE)),
Span::raw(&app.system_info.hostname),
]),
Line::from(vec![
Span::styled("OS: ", Style::default().fg(glances_colors::TITLE)),
Span::raw(&app.system_info.os),
]),
Line::from(vec![
Span::styled("Kernel: ", Style::default().fg(glances_colors::TITLE)),
Span::raw(app.system_info.kernel.as_deref().unwrap_or("--")),
]),
Line::from(vec![
Span::styled("Uptime: ", Style::default().fg(glances_colors::TITLE)),
Span::raw(uptime_text),
]),
];
if let Some(ref manufacturer) = app.system_info.manufacturer {
sys_lines.push(Line::from(vec![
Span::styled("Manufacturer: ", Style::default().fg(glances_colors::TITLE)),
Span::raw(manufacturer),
]));
}
if let Some(ref model) = app.system_info.model {
sys_lines.push(Line::from(vec![
Span::styled("Model: ", Style::default().fg(glances_colors::TITLE)),
Span::raw(model),
]));
}
let sys_info = Paragraph::new(sys_lines)
.block(
Block::default()
.borders(Borders::ALL)
.title("System Information"),
)
.style(Style::default().fg(Color::White));
f.render_widget(sys_info, chunks[0]);
draw_disk_bar(f, app, chunks[1]);
let disk_items: Vec<ListItem> = app
.disk_info
.iter()
.map(|disk| {
let percent = disk_percent(disk.used, disk.total);
let io_str = match (disk.read_rate, disk.write_rate) {
(Some(r), Some(w)) if r > 0.0 || w > 0.0 => {
format!(" │ R:{}/s W:{}/s", auto_unit(r as u64), auto_unit(w as u64))
}
_ => String::new(),
};
ListItem::new(Line::from(vec![
Span::styled(
format!("{}: ", disk.name),
Style::default().fg(glances_colors::DISK_TITLE),
),
Span::styled(
format!(
"{} / {} ({})",
gb_or_unknown(disk.used),
gb_or_unknown(disk.total),
percent_or_unknown(percent)
),
Style::default().fg(disk_color(percent.unwrap_or(0.0) as f32)),
),
Span::raw(format!(
" │ {} │ {}{}",
if disk.filesystem.is_empty() {
"unknown"
} else {
disk.filesystem.as_str()
},
disk.mount_point,
io_str
)),
]))
})
.collect();
let disks = List::new(disk_items)
.block(Block::default().borders(Borders::ALL).title("Disks"))
.style(Style::default().fg(Color::White));
f.render_widget(disks, chunks[2]);
draw_network_bar(f, app, chunks[3]);
let net_items: Vec<ListItem> = app
.network_info
.interfaces
.iter()
.map(|iface| {
let speed = iface
.speed_mbps
.map(|s| format!(" {}Mbps", s))
.unwrap_or_default();
let (status, status_color) = match iface.is_up {
Some(true) => ("UP", glances_colors::OK),
Some(false) => ("DOWN", glances_colors::CRITICAL),
None => ("unknown", glances_colors::INACTIVE),
};
ListItem::new(Line::from(vec![
Span::styled(
format!("{}: ", iface.name),
Style::default().fg(glances_colors::NETWORK_TITLE),
),
Span::styled(status, Style::default().fg(status_color)),
Span::raw(format!(
"{} │ ↓{} ↑{} │ Total: ↓{} ↑{}",
speed,
format_bandwidth(iface.rx_rate),
format_bandwidth(iface.tx_rate),
auto_unit(iface.rx_bytes),
auto_unit(iface.tx_bytes),
)),
]))
})
.collect();
let net_list = List::new(net_items)
.block(
Block::default()
.borders(Borders::ALL)
.title("Network Interfaces"),
)
.style(Style::default().fg(Color::White));
f.render_widget(net_list, chunks[4]);
draw_network_context(f, app, chunks[5]);
}
fn draw_network_context(f: &mut Frame, app: &App, area: Rect) {
let label = |s: &str| {
Span::styled(
format!("{s:<9}"),
Style::default().fg(glances_colors::NETWORK_TITLE),
)
};
let unread = |why: &str| {
Span::styled(
format!("not read: {why}"),
Style::default().fg(Color::DarkGray),
)
};
let lines: Vec<Line> = match &app.net_context {
None => vec![Line::from("Loading gateways, DNS and Wi-Fi...")],
Some(ctx) => {
let gateways = match &ctx.gateways {
Ok(g) if g.is_empty() => unread("no default route"),
Ok(g) => Span::raw(
g.iter()
.map(|g| {
let mut s = g.address.clone();
if let Some(i) = &g.interface {
s.push_str(&format!(" via {i}"));
}
if let Some(m) = &g.mac {
s.push_str(&format!(" ({m})"));
}
s
})
.collect::<Vec<_>>()
.join(" │ "),
),
Err(e) => unread(e),
};
let dns = match &ctx.dns_servers {
Ok(s) if s.is_empty() => unread("no DNS servers configured"),
Ok(s) => Span::raw(s.join(", ")),
Err(e) => unread(e),
};
let wifi = match &ctx.wifi {
Ok(w) if w.is_empty() => vec![unread("no Wi-Fi interface")],
Ok(w) => w
.iter()
.map(|w| {
let mut s = format!(
"{}: {}",
w.interface,
w.state.as_deref().unwrap_or("state not reported")
);
if w.connected == Some(true) {
s.push_str(&format!(
" │ SSID {} │ BSSID {}",
w.ssid.as_deref().unwrap_or("—"),
w.bssid.as_deref().unwrap_or("—")
));
if let Some(c) = w.channel {
s.push_str(&format!(" │ ch {c}"));
}
if let Some(b) = &w.band {
s.push_str(&format!(" {b}"));
}
if let Some(p) = w.signal_percent {
s.push_str(&format!(" │ {p}%"));
}
if let Some(r) = w.rssi_dbm {
s.push_str(&format!(" {r} dBm"));
}
if let Some(a) = &w.authentication {
s.push_str(&format!(" │ {a}"));
}
}
Span::raw(s)
})
.collect(),
Err(e) => vec![unread(e)],
};
let mut lines = vec![
Line::from(vec![label("Gateway"), gateways]),
Line::from(vec![label("DNS"), dns]),
];
for span in wifi {
lines.push(Line::from(vec![label("Wi-Fi"), span]));
}
lines
}
};
let panel = Paragraph::new(lines)
.block(
Block::default()
.borders(Borders::ALL)
.title("Network Context"),
)
.style(Style::default().fg(Color::White));
f.render_widget(panel, area);
}
fn draw_accelerators(f: &mut Frame, app: &App, area: Rect) {
if app.accelerators.is_empty() {
let message = if app.is_loading() {
"Detecting accelerators..."
} else {
"No accelerators detected"
};
let no_accel = Paragraph::new(message)
.block(Block::default().borders(Borders::ALL).title("Accelerators"))
.alignment(Alignment::Center);
f.render_widget(no_accel, area);
return;
}
let accel_count = app.accelerators.len();
let constraints: Vec<Constraint> =
std::iter::repeat_n(Constraint::Ratio(1, accel_count as u32), accel_count).collect();
let accel_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(constraints)
.split(area);
for (idx, accel) in app.accelerators.iter().enumerate() {
draw_single_accelerator(f, accel, idx, accel_chunks[idx]);
}
}
fn draw_single_accelerator(
f: &mut Frame,
accel: &super::app::AcceleratorInfo,
idx: usize,
area: Rect,
) {
let type_str = format!("{}", accel.accel_type);
let pcie_str = match (accel.pcie_gen, accel.pcie_width) {
(Some(gen), Some(width)) => format!(" │ PCIe Gen{}x{}", gen, width),
_ => String::new(),
};
let block = Block::default().borders(Borders::ALL).title(Span::styled(
format!(
"{} {} │ {} ({}){}",
type_str, idx, accel.name, accel.vendor, pcie_str
),
Style::default()
.fg(glances_colors::ACCEL_TITLE)
.add_modifier(Modifier::BOLD),
));
let inner = block.inner(area);
f.render_widget(block, area);
let mem_percent = match (accel.memory_used, accel.memory_total) {
(Some(used), Some(total)) if total > 0 => Some((used as f64 / total as f64) * 100.0),
_ => None,
};
let fan_str = match (accel.fan_speed_rpm, accel.fan_speed_percent) {
(Some(rpm), _) => format!(" │ FAN:{}RPM", rpm),
(None, Some(pct)) => format!(" │ FAN:{:.0}%", pct),
(None, None) => String::new(),
};
let enc_dec_str = {
let enc = accel.encoder_util.filter(|&u| u > 0.5);
let dec = accel.decoder_util.filter(|&u| u > 0.5);
match (enc, dec) {
(Some(e), Some(d)) => format!(" │ ENC:{:.0}% DEC:{:.0}%", e, d),
(Some(e), None) => format!(" │ ENC:{:.0}%", e),
(None, Some(d)) => format!(" │ DEC:{:.0}%", d),
(None, None) => String::new(),
}
};
let accel_util_label = format!(
"{}: {} @ {} │ MEM: {}/{} ({}) @ {} │ {} │ {}{}{}",
type_str,
accel
.utilization
.map_or_else(|| "-".to_string(), |u| format!("{u:.0}%")),
mhz_opt(accel.clock_core),
auto_unit_opt(accel.memory_used),
auto_unit_opt(accel.memory_total),
pct_opt(mem_percent),
mhz_opt(accel.clock_memory),
celsius_opt(accel.temperature),
watts_opt(accel.power, accel.power_limit),
fan_str,
enc_dec_str
);
let accel_clr = accel.utilization.map_or(Color::DarkGray, accel_color);
let accel_gauge = Gauge::default()
.gauge_style(Style::default().fg(accel_clr).add_modifier(Modifier::BOLD))
.percent(safe_percent(accel.utilization.unwrap_or(0.0)))
.label(accel_util_label);
f.render_widget(accel_gauge, inner);
}
#[allow(dead_code)]
fn draw_nvtop_gpus(f: &mut Frame, app: &App, area: Rect) {
if app.gpu_info.is_empty() {
let no_gpu = Paragraph::new("No GPUs detected")
.block(Block::default().borders(Borders::ALL).title("GPUs"))
.alignment(Alignment::Center);
f.render_widget(no_gpu, area);
return;
}
let gpu_count = app.gpu_info.len();
let constraints: Vec<Constraint> =
std::iter::repeat_n(Constraint::Ratio(1, gpu_count as u32), gpu_count).collect();
let gpu_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints(constraints)
.split(area);
for (idx, gpu) in app.gpu_info.iter().enumerate() {
draw_single_gpu(f, gpu, idx, gpu_chunks[idx]);
}
}
#[allow(dead_code)]
fn draw_single_gpu(f: &mut Frame, gpu: &super::app::GpuInfo, idx: usize, area: Rect) {
let block = Block::default().borders(Borders::ALL).title(Span::styled(
format!("GPU {} │ {} ({})", idx, gpu.name, gpu.vendor),
Style::default()
.fg(glances_colors::ACCEL_TITLE)
.add_modifier(Modifier::BOLD),
));
let inner = block.inner(area);
f.render_widget(block, area);
let mem_percent = match (gpu.memory_used, gpu.memory_total) {
(Some(used), Some(total)) if total > 0 => Some((used as f64 / total as f64) * 100.0),
_ => None,
};
let gpu_util_label = format!(
"GPU: {} @ {} │ MEM: {}/{} ({}) @ {} │ {} │ {}",
pct_opt(gpu.utilization.map(f64::from)),
mhz_opt(gpu.clock_graphics),
auto_unit_opt(gpu.memory_used),
auto_unit_opt(gpu.memory_total),
pct_opt(mem_percent),
mhz_opt(gpu.clock_memory),
celsius_opt(gpu.temperature),
watts_opt(gpu.power, gpu.power_limit)
);
let gpu_clr = gpu.utilization.map_or(Color::DarkGray, accel_color);
let gpu_gauge = Gauge::default()
.gauge_style(Style::default().fg(gpu_clr).add_modifier(Modifier::BOLD))
.percent(safe_percent(gpu.utilization.unwrap_or(0.0)))
.label(gpu_util_label);
f.render_widget(gpu_gauge, inner);
}
#[allow(dead_code)]
fn draw_system_graphs(f: &mut Frame, app: &App, area: Rect) {
let graph_chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(3), Constraint::Length(3), Constraint::Length(3), Constraint::Length(3), ])
.split(area);
draw_cpu_bar(f, app, graph_chunks[0]);
draw_memory_bar(f, app, graph_chunks[1]);
draw_disk_bar(f, app, graph_chunks[2]);
draw_network_bar(f, app, graph_chunks[3]);
}
fn draw_cpu_bar(f: &mut Frame, app: &App, area: Rect) {
let prev_cpu = app.cpu_history.iter().rev().nth(1).map(|&v| v as f32);
let trend_arrow = match app.cpu_info.utilization {
Some(cpu) => trend_indicator(cpu, prev_cpu.unwrap_or(cpu)).0,
None => "",
};
let per_core_display: String = if !app.cpu_info.per_core_usage.is_empty() {
let cores_to_show = app.cpu_info.per_core_usage.len().min(16);
let mini_bars: String = app.cpu_info.per_core_usage[..cores_to_show]
.iter()
.map(|&u| {
let Some(u) = u else {
return '?';
};
match u as u32 {
0..=12 => '▁',
13..=25 => '▂',
26..=37 => '▃',
38..=50 => '▄',
51..=62 => '▅',
63..=75 => '▆',
76..=87 => '▇',
_ => '█',
}
})
.collect();
if app.cpu_info.per_core_usage.len() > 16 {
format!("[{}…]", mini_bars)
} else {
format!("[{}]", mini_bars)
}
} else {
String::new()
};
let cpu_pct_text = app
.cpu_info
.utilization
.map_or_else(|| "--".to_string(), |u| format!("{u:.0}%"));
let cpu_label = format!(
"CPU {} {} │ {}{}{} {}",
trend_arrow,
cpu_pct_text,
cores_text(&app.cpu_info),
opt_mhz(app.cpu_info.frequency, " @ "),
opt_celsius(app.cpu_info.temperature, " │ "),
per_core_display
);
let cpu_clr = app.cpu_info.utilization.map_or(Color::DarkGray, cpu_color);
let cpu_gauge = Gauge::default()
.block(
Block::default().borders(Borders::ALL).title(Span::styled(
"CPU",
Style::default()
.fg(glances_colors::CPU_TITLE)
.add_modifier(Modifier::BOLD),
)),
)
.gauge_style(Style::default().fg(cpu_clr).add_modifier(Modifier::BOLD))
.percent(safe_percent(app.cpu_info.utilization.unwrap_or(0.0)))
.label(cpu_label);
f.render_widget(cpu_gauge, area);
}
fn draw_memory_bar(f: &mut Frame, app: &App, area: Rect) {
let mem_percent = disk_percent(app.memory_info.used, app.memory_info.total);
let prev_mem = app.memory_history.iter().rev().nth(1).map(|&v| v as f32);
let trend_arrow = match mem_percent {
Some(mem) => trend_indicator(mem as f32, prev_mem.unwrap_or(mem as f32)).0,
None => "",
};
let mem_pct_text = mem_percent.map_or_else(|| "--".to_string(), |p| format!("{p:.0}%"));
let mem_label = format!(
"MEM {} {} │ {}/{} │ SWAP: {}",
trend_arrow,
mem_pct_text,
auto_unit_or_unknown(app.memory_info.used),
auto_unit_or_unknown(app.memory_info.total),
auto_unit_opt(app.memory_info.swap_used)
);
let mem_clr = mem_percent.map_or(Color::DarkGray, |p| memory_color(p as f32));
let mem_gauge = Gauge::default()
.block(
Block::default().borders(Borders::ALL).title(Span::styled(
"Memory",
Style::default()
.fg(glances_colors::MEMORY_TITLE)
.add_modifier(Modifier::BOLD),
)),
)
.gauge_style(Style::default().fg(mem_clr).add_modifier(Modifier::BOLD))
.percent(safe_percent(mem_percent.unwrap_or(0.0) as f32))
.label(mem_label);
f.render_widget(mem_gauge, area);
}
fn gb_or_unknown(bytes: Option<u64>) -> String {
match bytes {
Some(b) => format!("{:.1} GB", b as f64 / (1024.0 * 1024.0 * 1024.0)),
None => "-- GB".to_string(),
}
}
fn disk_percent(used: Option<u64>, total: Option<u64>) -> Option<f64> {
match (used, total) {
(Some(used), Some(total)) if total > 0 => Some((used as f64 / total as f64) * 100.0),
_ => None,
}
}
fn percent_or_unknown(percent: Option<f64>) -> String {
match percent {
Some(p) => format!("{:.0}%", p),
None => "--%".to_string(),
}
}
fn draw_disk_bar(f: &mut Frame, app: &App, area: Rect) {
let total_space: Option<u64> = app.disk_info.iter().map(|d| d.total).sum();
let used_space: Option<u64> = app.disk_info.iter().map(|d| d.used).sum();
let total_read: f64 = app.disk_info.iter().filter_map(|d| d.read_rate).sum();
let total_write: f64 = app.disk_info.iter().filter_map(|d| d.write_rate).sum();
let fleet_percent = disk_percent(used_space, total_space);
let disk_list: Vec<String> = app
.disk_info
.iter()
.take(3)
.map(|d| {
format!(
"{}:{}",
d.name.chars().take(20).collect::<String>(),
percent_or_unknown(disk_percent(d.used, d.total))
)
})
.collect();
let io_str = if total_read > 0.0 || total_write > 0.0 {
format!(
" │ R:{}/s W:{}/s",
auto_unit(total_read as u64),
auto_unit(total_write as u64)
)
} else {
String::new()
};
let share = percent_or_unknown(fleet_percent);
let used_label = auto_unit_or_unknown(used_space);
let total_label = auto_unit_or_unknown(total_space);
let disk_label = if !disk_list.is_empty() {
format!(
"DISK {} │ {}/{}{}│ {}",
share,
used_label,
total_label,
io_str,
disk_list.join(" ")
)
} else {
format!(
"DISK {} │ {}/{}{} │ No disks",
share, used_label, total_label, io_str
)
};
let filled = fleet_percent.unwrap_or(0.0) as f32;
let disk_clr = disk_color(filled);
let disk_gauge = Gauge::default()
.block(
Block::default().borders(Borders::ALL).title(Span::styled(
"Disk",
Style::default()
.fg(glances_colors::DISK_TITLE)
.add_modifier(Modifier::BOLD),
)),
)
.gauge_style(Style::default().fg(disk_clr).add_modifier(Modifier::BOLD))
.percent(safe_percent(filled))
.label(disk_label);
f.render_widget(disk_gauge, area);
}
fn draw_network_bar(f: &mut Frame, app: &App, area: Rect) {
let net_info = &app.network_info;
let rx_rate = format_bandwidth(net_info.total_rx_rate);
let tx_rate = format_bandwidth(net_info.total_tx_rate);
let mut active_ifaces: Vec<_> = net_info
.interfaces
.iter()
.filter(|i| {
let idle = matches!(
(i.rx_rate, i.tx_rate),
(Some(rx), Some(tx)) if rx <= 0.0 && tx <= 0.0
);
i.is_up == Some(true) && !idle
})
.collect();
active_ifaces.sort_by(|a, b| {
let a_total = a.rx_rate.unwrap_or(0.0) + a.tx_rate.unwrap_or(0.0);
let b_total = b.rx_rate.unwrap_or(0.0) + b.tx_rate.unwrap_or(0.0);
b_total
.partial_cmp(&a_total)
.unwrap_or(std::cmp::Ordering::Equal)
});
let iface_list: String = if !active_ifaces.is_empty() {
active_ifaces
.iter()
.take(2)
.map(|i| {
let speed = i
.speed_mbps
.map(|s| format!(" {}Mb", s))
.unwrap_or_default();
format!(
"{}{}↓{} ↑{}",
i.name.chars().take(8).collect::<String>(),
speed,
format_bandwidth(i.rx_rate),
format_bandwidth(i.tx_rate)
)
})
.collect::<Vec<_>>()
.join(" │ ")
} else if !net_info.interfaces.is_empty() {
net_info
.interfaces
.iter()
.take(2)
.map(|i| i.name.clone())
.collect::<Vec<_>>()
.join(", ")
} else {
"No interfaces".to_string()
};
let net_label = format!(
"NET ↓{} ↑{} │ Total: ↓{} ↑{} │ {}",
rx_rate,
tx_rate,
auto_unit(net_info.total_rx_bytes),
auto_unit(net_info.total_tx_bytes),
iface_list
);
let known_total = match (net_info.total_rx_rate, net_info.total_tx_rate) {
(Some(rx), Some(tx)) => Some(rx + tx),
_ => None,
};
let gauge_percent = known_total.map_or(0, |total| {
let max_rate = total.max(1.0);
((max_rate.log10() + 3.0) * 10.0).clamp(0.0, 100.0) as u16
});
let net_clr = known_total.map_or(Color::DarkGray, |_| network_color(gauge_percent as f32));
let net_gauge = Gauge::default()
.block(
Block::default().borders(Borders::ALL).title(Span::styled(
"Network",
Style::default()
.fg(glances_colors::NETWORK_TITLE)
.add_modifier(Modifier::BOLD),
)),
)
.gauge_style(Style::default().fg(net_clr).add_modifier(Modifier::BOLD))
.percent(gauge_percent)
.label(net_label);
f.render_widget(net_gauge, area);
}
fn format_bandwidth(bytes_per_sec: Option<f64>) -> String {
let Some(bytes_per_sec) = bytes_per_sec else {
return "—".to_string();
};
const KB: f64 = 1024.0;
const MB: f64 = KB * 1024.0;
const GB: f64 = MB * 1024.0;
if bytes_per_sec >= GB {
format!("{:.1}G/s", bytes_per_sec / GB)
} else if bytes_per_sec >= MB {
format!("{:.1}M/s", bytes_per_sec / MB)
} else if bytes_per_sec >= KB {
format!("{:.0}K/s", bytes_per_sec / KB)
} else if bytes_per_sec > 0.0 {
format!("{:.0}B/s", bytes_per_sec)
} else {
"0B/s".to_string()
}
}
#[allow(dead_code)]
fn draw_cpu_graph(f: &mut Frame, app: &App, area: Rect) {
let inner_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Length(25), Constraint::Min(0), ])
.split(area);
let mut cpu_text = vec![
Line::from(match app.cpu_info.utilization {
Some(u) => format!("CPU: {u:.0}%"),
None => "CPU: --".to_string(),
}),
Line::from(cores_text(&app.cpu_info)),
];
if let Some(mhz) = app.cpu_info.frequency {
cpu_text.push(Line::from(format!("@ {mhz} MHz")));
}
let cpu_info = Paragraph::new(cpu_text)
.block(Block::default().borders(Borders::ALL).title("CPU"))
.style(Style::default().fg(Color::White));
f.render_widget(cpu_info, inner_chunks[0]);
let cpu_data: Vec<u64> = app.cpu_history.iter().copied().collect();
if !cpu_data.is_empty() {
let sparkline = Sparkline::default()
.block(Block::default().borders(Borders::TOP | Borders::RIGHT | Borders::BOTTOM))
.data(&cpu_data)
.style(
Style::default().fg(app
.cpu_info
.utilization
.map_or(Color::DarkGray, usage_color)),
);
f.render_widget(sparkline, inner_chunks[1]);
}
}
#[allow(dead_code)]
fn draw_memory_graph(f: &mut Frame, app: &App, area: Rect) {
let inner_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Length(25), Constraint::Min(0), ])
.split(area);
let mem_used_gb = app
.memory_info
.used
.map(|v| v as f64 / (1024.0 * 1024.0 * 1024.0));
let mem_total_gb = app
.memory_info
.total
.map(|v| v as f64 / (1024.0 * 1024.0 * 1024.0));
let mem_percent = disk_percent(app.memory_info.used, app.memory_info.total);
let mem_text = vec![
Line::from(match mem_percent {
Some(p) => format!("RAM: {:.0}%", p),
None => "RAM: --".to_string(),
}),
Line::from(match mem_used_gb {
Some(v) => format!("{:.1} GB", v),
None => "-- GB".to_string(),
}),
Line::from(match mem_total_gb {
Some(v) => format!("/ {:.1} GB", v),
None => "/ -- GB".to_string(),
}),
];
let mem_info = Paragraph::new(mem_text)
.block(Block::default().borders(Borders::ALL).title("Memory"))
.style(Style::default().fg(Color::White));
f.render_widget(mem_info, inner_chunks[0]);
let mem_data: Vec<u64> = app.memory_history.iter().copied().collect();
if !mem_data.is_empty() {
let sparkline = Sparkline::default()
.block(Block::default().borders(Borders::TOP | Borders::RIGHT | Borders::BOTTOM))
.data(&mem_data)
.style(
Style::default().fg(mem_percent.map_or(Color::DarkGray, |p| usage_color(p as f32))),
);
f.render_widget(sparkline, inner_chunks[1]);
}
}
#[allow(dead_code)]
fn draw_disk_graph(f: &mut Frame, app: &App, area: Rect) {
let inner_chunks = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Length(25), Constraint::Min(0), ])
.split(area);
let _total_disks = app.disk_info.len();
let total_space: Option<u64> = app.disk_info.iter().map(|d| d.total).sum();
let used_space: Option<u64> = app.disk_info.iter().map(|d| d.used).sum();
let disk_text = vec![
Line::from(format!(
"Disk: {}",
percent_or_unknown(disk_percent(used_space, total_space))
)),
Line::from(gb_or_unknown(used_space)),
Line::from(format!("/ {}", gb_or_unknown(total_space))),
];
let disk_info = Paragraph::new(disk_text)
.block(Block::default().borders(Borders::ALL).title("Disk"))
.style(Style::default().fg(Color::White));
f.render_widget(disk_info, inner_chunks[0]);
if !app.disk_info.is_empty() {
let disk_items: Vec<Span> = app
.disk_info
.iter()
.map(|disk| {
let percent = disk_percent(disk.used, disk.total);
Span::styled(
format!(" {}: {} ", disk.name, percent_or_unknown(percent)),
Style::default().fg(usage_color(percent.unwrap_or(0.0) as f32)),
)
})
.collect();
let disk_list = Paragraph::new(Line::from(disk_items))
.block(Block::default().borders(Borders::TOP | Borders::RIGHT | Borders::BOTTOM))
.style(Style::default().fg(Color::White));
f.render_widget(disk_list, inner_chunks[1]);
} else {
let no_disk = Paragraph::new("No disks detected")
.block(Block::default().borders(Borders::TOP | Borders::RIGHT | Borders::BOTTOM))
.style(Style::default().fg(Color::DarkGray))
.alignment(Alignment::Center);
f.render_widget(no_disk, inner_chunks[1]);
}
}
fn draw_nvtop_processes(f: &mut Frame, app: &App, area: Rect) {
let mode_name = app.process_mode_name();
let has_gpus = !app.accelerators.is_empty();
let scroll_pos = app.get_scroll_position();
let total_count = app.filtered_process_count;
let visible_count = 25;
let processes = app.get_visible_processes(scroll_pos, visible_count);
let selected_display_idx = if app.selected_process_idx >= scroll_pos
&& app.selected_process_idx < scroll_pos + visible_count
{
Some(app.selected_process_idx - scroll_pos)
} else {
None
};
let highlight_style = Style::default().bg(Color::Rgb(69, 71, 90));
let total_gpu_memory: u64 = app.accelerators.iter().filter_map(|a| a.memory_total).sum();
let (header, rows, widths) = match app.process_display_mode {
super::app::ProcessDisplayMode::All | super::app::ProcessDisplayMode::Cpu => {
let header = if has_gpus {
Row::new(vec![
Span::styled(
"PID",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"USER",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"S",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"COMMAND",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"CPU%",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"MEM",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"DEV",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"GPU%",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"GMEM",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"GM%",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"E/D",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"TY",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
])
.bottom_margin(1)
} else {
Row::new(vec![
Span::styled(
"PID",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"USER",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"S",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"COMMAND",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"CPU%",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"MEM",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"THR",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"I/O",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
])
.bottom_margin(1)
};
let rows: Vec<Row> = processes
.iter()
.enumerate()
.map(|(display_idx, p)| {
let is_selected = selected_display_idx == Some(display_idx);
let cpu_clr = p.cpu_percent.map_or(Color::DarkGray, cpu_color);
let gpu_clr = p.gpu_usage_percent.map_or(Color::DarkGray, accel_color);
let enc_clr = p.encoder_usage_percent.map_or(Color::DarkGray, accel_color);
let gpu_mem_percent = match p.total_gpu_memory_bytes {
Some(bytes) if total_gpu_memory > 0 && bytes > 0 => {
Some((bytes as f64 / total_gpu_memory as f64 * 100.0) as f32)
}
_ => p.gpu_memory_percentage,
};
let gpu_mem_pct_clr = gpu_mem_percent.map_or(Color::DarkGray, accel_color);
let gpu_mem_color = match p.total_gpu_memory_bytes {
Some(b) if b > 1024 * 1024 * 1024 => glances_colors::WARNING, Some(b) if b > 256 * 1024 * 1024 => glances_colors::CAREFUL, Some(b) if b > 0 => glances_colors::OK,
_ => Color::DarkGray,
};
let state_color = match p.state {
'R' => glances_colors::OK, 'S' => Color::White, 'D' => glances_colors::WARNING, 'Z' => glances_colors::CRITICAL, 'T' => glances_colors::CAREFUL, _ => Color::DarkGray,
};
let gpu_type_str = match p.gpu_process_type {
crate::process_monitor::ProcessGpuType::Graphical => "G",
crate::process_monitor::ProcessGpuType::Compute => "C",
crate::process_monitor::ProcessGpuType::GraphicalCompute => "M",
crate::process_monitor::ProcessGpuType::Unknown => "-",
};
if has_gpus {
let gpu_idx_str = match &p.gpu_indices {
None => "—".to_string(),
Some(gpus) if gpus.is_empty() => "-".to_string(),
Some(gpus) => gpus
.iter()
.map(|i| i.to_string())
.collect::<Vec<_>>()
.join(","),
};
let enc_dec_str = match (p.encoder_usage_percent, p.decoder_usage_percent) {
(Some(e), Some(d)) if e > 0.1 || d > 0.1 => {
format!("{:.0}/{:.0}", e, d)
}
(Some(e), None) if e > 0.1 => format!("{:.0}/-", e),
(None, Some(d)) if d > 0.1 => format!("-/{:.0}", d),
(Some(e), Some(d)) => format!("{:.0}/{:.0}", e, d),
(Some(e), None) => format!("{:.0}/-", e),
(None, Some(d)) => format!("-/{:.0}", d),
(None, None) => "-".to_string(),
};
Row::new(vec![
Span::styled(
format!("{:>7}", p.pid),
Style::default().fg(Color::White),
),
Span::styled(
format!(
"{:<8}",
p.user
.as_deref()
.unwrap_or("?")
.chars()
.take(8)
.collect::<String>()
),
Style::default().fg(Color::White),
),
Span::styled(format!("{}", p.state), Style::default().fg(state_color)),
Span::styled(
p.name.chars().take(18).collect::<String>(),
Style::default().fg(Color::White),
),
Span::styled(
p.cpu_percent.map_or_else(
|| format!("{:>6}", "--"),
|c| format!("{c:>5.1}%"),
),
Style::default().fg(cpu_clr),
),
Span::styled(
format!("{:>6}", auto_unit(p.memory_bytes)),
Style::default().fg(Color::White),
),
Span::styled(
gpu_idx_str,
Style::default().fg(if p.is_gpu_process() == Some(true) {
Color::Magenta
} else {
Color::DarkGray
}),
),
Span::styled(
p.gpu_usage_percent
.map(|u| format!("{:>4.0}%", u))
.unwrap_or_else(|| " -".to_string()),
Style::default().fg(gpu_clr),
),
Span::styled(
match p.total_gpu_memory_bytes {
Some(b) if b > 0 => format!("{:>5}", auto_unit(b)),
_ => " -".to_string(),
},
Style::default().fg(gpu_mem_color),
),
Span::styled(
gpu_mem_percent
.map(|u| format!("{:>4.1}%", u))
.unwrap_or_else(|| " -".to_string()),
Style::default().fg(gpu_mem_pct_clr),
),
Span::styled(
enc_dec_str,
Style::default().fg(
if p.encoder_usage_percent.is_some()
|| p.decoder_usage_percent.is_some()
{
enc_clr
} else {
Color::DarkGray
},
),
),
Span::styled(
gpu_type_str.to_string(),
Style::default().fg(if p.is_gpu_process() == Some(true) {
glances_colors::CAREFUL
} else {
glances_colors::INACTIVE
}),
),
])
.style(if is_selected {
highlight_style
} else {
Style::default()
})
} else {
let total_io = p.io_read_bytes.zip(p.io_write_bytes).map(|(r, w)| r + w);
let io_color = if total_io.is_none() {
Color::DarkGray
} else if total_io.unwrap_or(0) > 1024 * 1024 * 1024 {
glances_colors::WARNING } else if total_io.unwrap_or(0) > 100 * 1024 * 1024 {
glances_colors::CAREFUL } else if total_io.unwrap_or(0) > 0 {
glances_colors::OK
} else {
Color::DarkGray
};
let thread_color = if p.thread_count > 100 {
glances_colors::WARNING
} else if p.thread_count > 20 {
glances_colors::CAREFUL
} else if p.thread_count > 0 {
Color::White
} else {
Color::DarkGray
};
Row::new(vec![
Span::styled(
format!("{:>7}", p.pid),
Style::default().fg(Color::White),
),
Span::styled(
format!(
"{:<8}",
p.user
.as_deref()
.unwrap_or("?")
.chars()
.take(8)
.collect::<String>()
),
Style::default().fg(Color::White),
),
Span::styled(format!("{}", p.state), Style::default().fg(state_color)),
Span::styled(
p.name.chars().take(25).collect::<String>(),
Style::default().fg(Color::White),
),
Span::styled(
p.cpu_percent.map_or_else(
|| format!("{:>6}", "--"),
|c| format!("{c:>5.1}%"),
),
Style::default().fg(cpu_clr),
),
Span::styled(
format!("{:>6}", auto_unit(p.memory_bytes)),
Style::default().fg(Color::White),
),
Span::styled(
if p.thread_count > 0 {
format!("{:>4}", p.thread_count)
} else {
" -".to_string()
},
Style::default().fg(thread_color),
),
Span::styled(
match total_io {
Some(t) if t > 0 => format!("{:>6}", auto_unit(t)),
Some(_) => " -".to_string(),
None => " ?".to_string(),
},
Style::default().fg(io_color),
),
])
.style(if is_selected {
highlight_style
} else {
Style::default()
})
}
})
.collect();
let widths = if has_gpus {
vec![
Constraint::Length(8), Constraint::Length(9), Constraint::Length(2), Constraint::Min(10), Constraint::Length(7), Constraint::Length(7), Constraint::Length(4), Constraint::Length(6), Constraint::Length(6), Constraint::Length(6), Constraint::Length(6), Constraint::Length(2), ]
} else {
vec![
Constraint::Length(8), Constraint::Length(9), Constraint::Length(2), Constraint::Min(15), Constraint::Length(7), Constraint::Length(7), Constraint::Length(5), Constraint::Length(7), ]
};
(header, rows, widths)
}
super::app::ProcessDisplayMode::Gpu(gpu_idx) => {
let header = Row::new(vec![
Span::styled(
"PID",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"USER",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"COMMAND",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"GPU MEM",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"GPU%",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"TYPE",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
])
.bottom_margin(1);
let rows: Vec<Row> = processes
.iter()
.enumerate()
.map(|(display_idx, p)| {
let is_selected = selected_display_idx == Some(display_idx);
let gpu_mem = p
.gpu_memory_per_device
.get(&gpu_idx)
.map(|&m| auto_unit(m))
.unwrap_or_else(|| "0B".to_string());
let gpu_usage = p
.gpu_usage_percent
.map(|u| format!("{:>5.1}%", u))
.unwrap_or_else(|| " N/A".to_string());
let gpu_clr = p.gpu_usage_percent.map_or(Color::DarkGray, accel_color);
let proc_type = format!("{:?}", p.gpu_process_type);
Row::new(vec![
Span::styled(format!("{:>7}", p.pid), Style::default().fg(Color::White)),
Span::styled(
format!(
"{:<10}",
p.user
.as_deref()
.unwrap_or("?")
.chars()
.take(10)
.collect::<String>()
),
Style::default().fg(Color::White),
),
Span::styled(p.name.clone(), Style::default().fg(Color::White)),
Span::styled(format!("{:>7}", gpu_mem), Style::default().fg(gpu_clr)),
Span::styled(gpu_usage, Style::default().fg(gpu_clr)),
Span::styled(proc_type, Style::default().fg(glances_colors::INACTIVE)),
])
.style(if is_selected {
highlight_style
} else {
Style::default()
})
})
.collect();
let widths = vec![
Constraint::Length(8), Constraint::Length(11), Constraint::Min(15), Constraint::Length(10), Constraint::Length(8), Constraint::Length(10), ];
(header, rows, widths)
}
super::app::ProcessDisplayMode::Npu(_) => {
let header = Row::new(vec![Span::styled(
"No NPU processes available",
Style::default().fg(glances_colors::INACTIVE),
)]);
let widths = vec![Constraint::Percentage(100)];
(header, vec![], widths)
}
super::app::ProcessDisplayMode::Accelerator(accel_idx) => {
let header = Row::new(vec![
Span::styled(
"PID",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"USER",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"COMMAND",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"ACCEL MEM",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"ACCEL%",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
Span::styled(
"TYPE",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD | Modifier::UNDERLINED),
),
])
.bottom_margin(1);
let rows: Vec<Row> = processes
.iter()
.enumerate()
.map(|(display_idx, p)| {
let is_selected = selected_display_idx == Some(display_idx);
let accel_mem = p
.gpu_memory_per_device
.get(&accel_idx)
.map(|&m| auto_unit(m))
.unwrap_or_else(|| "0B".to_string());
let accel_usage = p
.gpu_usage_percent
.map(|u| format!("{:>5.1}%", u))
.unwrap_or_else(|| " N/A".to_string());
let accel_clr = p.gpu_usage_percent.map_or(Color::DarkGray, accel_color);
let proc_type = format!("{:?}", p.gpu_process_type);
Row::new(vec![
Span::styled(format!("{:>7}", p.pid), Style::default().fg(Color::White)),
Span::styled(
format!(
"{:<10}",
p.user
.as_deref()
.unwrap_or("?")
.chars()
.take(10)
.collect::<String>()
),
Style::default().fg(Color::White),
),
Span::styled(p.name.clone(), Style::default().fg(Color::White)),
Span::styled(format!("{:>9}", accel_mem), Style::default().fg(accel_clr)),
Span::styled(accel_usage, Style::default().fg(accel_clr)),
Span::styled(proc_type, Style::default().fg(glances_colors::INACTIVE)),
])
.style(if is_selected {
highlight_style
} else {
Style::default()
})
})
.collect();
let widths = vec![
Constraint::Length(8), Constraint::Length(11), Constraint::Min(15), Constraint::Length(10), Constraint::Length(8), Constraint::Length(10), ];
(header, rows, widths)
}
};
let title = if scroll_pos > 0 {
format!(
"Processes - {} ({}-{} of {})",
mode_name,
scroll_pos + 1,
(scroll_pos + visible_count).min(total_count),
total_count
)
} else {
format!(
"Processes - {} ({} of {})",
mode_name,
visible_count.min(total_count),
total_count
)
};
let table = Table::new(rows, widths)
.header(header)
.block(Block::default().borders(Borders::ALL).title(title))
.column_spacing(1);
f.render_widget(table, area);
}
fn draw_tab_footer(f: &mut Frame, app: &App, area: Rect) {
if let Some(status_msg) = app.get_status_message() {
let status = Paragraph::new(Line::from(vec![Span::styled(
status_msg,
Style::default()
.fg(glances_colors::OK)
.add_modifier(Modifier::BOLD),
)]))
.block(Block::default().borders(Borders::ALL))
.alignment(Alignment::Center);
f.render_widget(status, area);
return;
}
if app.agent_input_mode {
let input_text = format!("> {}", app.agent_input);
let input = Paragraph::new(Line::from(vec![
Span::styled(
"Agent Query: ",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD),
),
Span::raw(&input_text),
Span::styled(
"█",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::SLOW_BLINK),
),
]))
.block(Block::default().borders(Borders::ALL))
.alignment(Alignment::Left);
f.render_widget(input, area);
return;
}
let mut help_spans = vec![
Span::styled(
"Tab",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD),
),
Span::raw(" Navigate "),
Span::styled(
"1-9 0",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD),
),
Span::raw(" Jump "),
Span::styled(
"q",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD),
),
Span::raw(" Quit "),
];
match app.selected_tab {
TAB_PROCESSES => {
help_spans.extend([
Span::styled(
"↑↓",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD),
),
Span::raw(" Select "),
Span::styled(
"Enter",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD),
),
Span::raw(" Detail "),
Span::styled(
"p",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD),
),
Span::raw(" Filter "),
Span::styled(
"PgUp/Dn",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD),
),
Span::raw(" Page "),
]);
}
TAB_AGENTS => {
help_spans.extend([
Span::styled(
"Up/Dn PgUp/Dn",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD),
),
Span::raw(" Scroll "),
]);
}
TAB_INFERENCE | TAB_AGENT => {
help_spans.extend([
Span::styled(
"a",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD),
),
Span::raw(" Ask "),
Span::styled(
"c",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD),
),
Span::raw(" Clear "),
]);
}
_ => {}
}
help_spans.extend([
Span::styled(
"t",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD),
),
Span::raw(" Theme "),
Span::styled("│", Style::default().fg(glances_colors::SEPARATOR)),
Span::raw(" "),
Span::styled("OK", Style::default().fg(glances_colors::OK)),
Span::raw(" "),
Span::styled("CAREFUL", Style::default().fg(glances_colors::CAREFUL)),
Span::raw(" "),
Span::styled("WARNING", Style::default().fg(glances_colors::WARNING)),
Span::raw(" "),
Span::styled("CRITICAL", Style::default().fg(glances_colors::CRITICAL)),
]);
let help = Paragraph::new(Line::from(help_spans))
.block(Block::default().borders(Borders::ALL))
.alignment(Alignment::Center);
f.render_widget(help, area);
}
#[allow(dead_code)]
fn draw_header(f: &mut Frame, app: &App, area: Rect) {
let titles: Vec<Line> = app.tabs.iter().map(|t| Line::from(*t)).collect();
let tabs = Tabs::new(titles)
.block(Block::default().borders(Borders::ALL).title("IronMonitor"))
.select(app.selected_tab)
.style(Style::default().fg(Color::Cyan))
.highlight_style(
Style::default()
.add_modifier(Modifier::BOLD)
.bg(Color::Cyan)
.fg(Color::Black),
);
f.render_widget(tabs, area);
}
#[allow(dead_code)]
fn draw_content(f: &mut Frame, app: &App, area: Rect) {
match app.selected_tab {
0 => draw_overview(f, app, area),
1 => draw_cpu(f, app, area),
2 => draw_gpu(f, app, area),
3 => draw_memory(f, app, area),
4 => draw_peripherals(f, app, area),
5 => draw_system(f, app, area),
6 => draw_agent(f, app, area),
_ => {}
}
}
#[allow(dead_code)]
fn draw_overview(f: &mut Frame, app: &App, area: Rect) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage(33),
Constraint::Percentage(33),
Constraint::Percentage(34),
])
.split(area);
let cpu_block = Block::default()
.borders(Borders::ALL)
.title(format!("CPU - {}", app.cpu_info.name));
let cpu_gauge = Gauge::default()
.block(cpu_block)
.gauge_style(
Style::default()
.fg(app.cpu_info.utilization.map_or(Color::DarkGray, cpu_color))
.bg(Color::Black)
.add_modifier(Modifier::BOLD),
)
.percent(safe_percent(app.cpu_info.utilization.unwrap_or(0.0)))
.label(format!(
"{} | {}{}",
app.cpu_info
.utilization
.map_or_else(|| "--".to_string(), |u| format!("{u:.1}%")),
cores_text(&app.cpu_info),
opt_celsius(app.cpu_info.temperature, " | ")
));
f.render_widget(cpu_gauge, chunks[0]);
let mem_percent = disk_percent(app.memory_info.used, app.memory_info.total);
let mem_block = Block::default().borders(Borders::ALL).title("Memory");
let mem_gauge = Gauge::default()
.block(mem_block)
.gauge_style(
Style::default()
.fg(mem_percent.map_or(Color::DarkGray, |p| usage_color(p as f32)))
.bg(Color::Black)
.add_modifier(Modifier::BOLD),
)
.percent(safe_percent(mem_percent.unwrap_or(0.0) as f32))
.label(
match (app.memory_info.used, app.memory_info.total, mem_percent) {
(Some(used), Some(total), Some(p)) => format!(
"{:.1} GB / {:.1} GB ({:.0}%)",
used as f64 / (1024.0 * 1024.0 * 1024.0),
total as f64 / (1024.0 * 1024.0 * 1024.0),
p
),
_ => "-- GB / -- GB (--)".to_string(),
},
);
f.render_widget(mem_gauge, chunks[1]);
if !app.gpu_info.is_empty() {
let gpu = &app.gpu_info[0];
let gpu_block = Block::default()
.borders(Borders::ALL)
.title(format!("GPU - {} ({})", gpu.name, gpu.vendor));
let gpu_gauge = Gauge::default()
.block(gpu_block)
.gauge_style(
Style::default()
.fg(gpu.utilization.map_or(Color::DarkGray, usage_color))
.bg(Color::Black)
.add_modifier(Modifier::BOLD),
)
.percent(safe_percent(gpu.utilization.unwrap_or(0.0)))
.label(format!(
"{} | {} | {}",
pct_opt(gpu.utilization.map(f64::from)),
celsius_opt(gpu.temperature),
watts_opt(gpu.power, gpu.power_limit)
));
f.render_widget(gpu_gauge, chunks[2]);
} else {
let no_gpu = Paragraph::new("No GPUs detected")
.block(Block::default().borders(Borders::ALL).title("GPU"))
.alignment(Alignment::Center);
f.render_widget(no_gpu, chunks[2]);
}
}
#[allow(dead_code)]
fn draw_cpu(f: &mut Frame, app: &App, area: Rect) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Percentage(40), Constraint::Percentage(60)])
.split(area);
let mut info_text = vec![
Line::from(format!("Name: {}", app.cpu_info.name)),
Line::from(match app.cpu_info.cores {
Some(cores) => format!(
"Cores: {} ({} threads)",
cores,
threads_text(app.cpu_info.threads)
),
None => format!(
"Cores: not reported ({} threads)",
threads_text(app.cpu_info.threads)
),
}),
Line::from(match app.cpu_info.utilization {
Some(u) => format!("Utilization: {u:.1}%"),
None => "Utilization: not measured".to_string(),
}),
];
info_text.push(Line::from(match app.cpu_info.temperature {
Some(c) => format!("Temperature: {c:.1}°C"),
None => "Temperature: not measured".to_string(),
}));
info_text.push(Line::from(match app.cpu_info.frequency {
Some(mhz) => format!("Frequency: {mhz} MHz"),
None => "Frequency: not measured".to_string(),
}));
let info = Paragraph::new(info_text)
.block(
Block::default()
.borders(Borders::ALL)
.title("CPU Information"),
)
.style(Style::default().fg(Color::White));
f.render_widget(info, chunks[0]);
let sparkline_data: Vec<u64> = app.cpu_history.iter().copied().collect();
let sparkline = Sparkline::default()
.block(
Block::default()
.borders(Borders::ALL)
.title("CPU History (60s)"),
)
.data(&sparkline_data)
.style(Style::default().fg(Color::Cyan));
f.render_widget(sparkline, chunks[1]);
}
#[allow(dead_code)]
fn draw_gpu(f: &mut Frame, app: &App, area: Rect) {
if app.gpu_info.is_empty() {
let no_gpu = Paragraph::new("No GPUs detected")
.block(Block::default().borders(Borders::ALL).title("GPU"))
.alignment(Alignment::Center);
f.render_widget(no_gpu, area);
return;
}
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
.split(area);
let gpu = &app.gpu_info[0];
let mem_percent = match (gpu.memory_used, gpu.memory_total) {
(Some(used), Some(total)) if total > 0 => {
Some(((used as f64 / total as f64) * 100.0).clamp(0.0, 100.0) as u16)
}
_ => None,
};
let info_text = vec![
Line::from(format!("Name: {}", gpu.name)),
Line::from(format!("Vendor: {}", gpu.vendor)),
Line::from(format!(
"Utilization: {}",
pct_opt(gpu.utilization.map(f64::from))
)),
Line::from(format!("Temperature: {}", celsius_opt(gpu.temperature))),
Line::from(format!("Power: {}", watts_opt(gpu.power, gpu.power_limit))),
Line::from(match (gpu.memory_used, gpu.memory_total, mem_percent) {
(Some(used), Some(total), Some(pct)) => format!(
"Memory: {:.1} GB / {:.1} GB ({}%)",
used as f64 / (1024.0 * 1024.0 * 1024.0),
total as f64 / (1024.0 * 1024.0 * 1024.0),
pct
),
(Some(used), None, _) => format!(
"Memory: {:.1} GB used, capacity not reported",
used as f64 / (1024.0 * 1024.0 * 1024.0)
),
_ => "Memory: not reported".to_string(),
}),
Line::from(format!(
"Graphics Clock: {} MHz",
gpu.clock_graphics
.map(|c| c.to_string())
.unwrap_or_else(|| "N/A".to_string())
)),
Line::from(format!(
"Memory Clock: {} MHz",
gpu.clock_memory
.map(|c| c.to_string())
.unwrap_or_else(|| "N/A".to_string())
)),
];
let info = Paragraph::new(info_text)
.block(
Block::default()
.borders(Borders::ALL)
.title("GPU Information"),
)
.style(Style::default().fg(Color::White));
f.render_widget(info, chunks[0]);
if !app.gpu_histories.is_empty() {
let sparkline_data: Vec<u64> = app.gpu_histories[0].iter().copied().collect();
let sparkline = Sparkline::default()
.block(
Block::default()
.borders(Borders::ALL)
.title("GPU Utilization History (60s)"),
)
.data(&sparkline_data)
.style(Style::default().fg(Color::Green));
f.render_widget(sparkline, chunks[1]);
}
}
#[allow(dead_code)]
fn draw_memory(f: &mut Frame, app: &App, area: Rect) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Percentage(40), Constraint::Percentage(60)])
.split(area);
let used_gb = app
.memory_info
.used
.map(|v| v as f64 / (1024.0 * 1024.0 * 1024.0));
let total_gb = app
.memory_info
.total
.map(|v| v as f64 / (1024.0 * 1024.0 * 1024.0));
let avail_gb = app
.memory_info
.available
.map(|v| v as f64 / (1024.0 * 1024.0 * 1024.0));
let swap_used_gb = app
.memory_info
.swap_used
.map(|v| v as f64 / (1024.0 * 1024.0 * 1024.0));
let swap_total_gb = app
.memory_info
.swap_total
.map(|v| v as f64 / (1024.0 * 1024.0 * 1024.0));
let info_text = vec![
Line::from(match total_gb {
Some(v) => format!("Total: {v:.2} GB"),
None => "Total: -- GB".to_string(),
}),
Line::from(match used_gb {
Some(v) => format!("Used: {v:.2} GB"),
None => "Used: -- GB".to_string(),
}),
Line::from(match avail_gb {
Some(v) => format!("Available: {v:.2} GB"),
None => "Available: -- GB".to_string(),
}),
Line::from(
match disk_percent(app.memory_info.used, app.memory_info.total) {
Some(p) => format!("Usage: {p:.1}%"),
None => "Usage: --".to_string(),
},
),
Line::from(""),
Line::from(match swap_total_gb {
Some(v) => format!("Swap Total: {v:.2} GB"),
None => "Swap Total: not reported".to_string(),
}),
Line::from(match swap_used_gb {
Some(v) => format!("Swap Used: {v:.2} GB"),
None => "Swap Used: not reported".to_string(),
}),
];
let info = Paragraph::new(info_text)
.block(
Block::default()
.borders(Borders::ALL)
.title("Memory Information"),
)
.style(Style::default().fg(Color::White));
f.render_widget(info, chunks[0]);
let sparkline_data: Vec<u64> = app.memory_history.iter().copied().collect();
let sparkline = Sparkline::default()
.block(
Block::default()
.borders(Borders::ALL)
.title("Memory Usage History (60s)"),
)
.data(&sparkline_data)
.style(Style::default().fg(Color::Magenta));
f.render_widget(sparkline, chunks[1]);
}
#[allow(dead_code)]
fn draw_system(f: &mut Frame, app: &App, area: Rect) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
.split(area);
let uptime_text = uptime_opt(app.system_info.uptime);
let kernel_text = app.system_info.kernel.as_deref().unwrap_or("--");
let mut info_lines = vec![
Line::from(format!("Hostname: {}", app.system_info.hostname)),
Line::from(format!("OS: {}", app.system_info.os)),
Line::from(format!("Kernel: {}", kernel_text)),
Line::from(format!("Uptime: {}", uptime_text)),
];
if let Some(ref manufacturer) = app.system_info.manufacturer {
info_lines.push(Line::from(format!("Manufacturer: {}", manufacturer)));
}
if let Some(ref model) = app.system_info.model {
info_lines.push(Line::from(format!("Model: {}", model)));
}
let info = Paragraph::new(info_lines)
.block(
Block::default()
.borders(Borders::ALL)
.title("System Information"),
)
.style(Style::default().fg(Color::White));
f.render_widget(info, chunks[0]);
let disk_items: Vec<ListItem> = app
.disk_info
.iter()
.map(|disk| {
ListItem::new(format!(
"{}: {} / {} ({}) - {}",
disk.name,
gb_or_unknown(disk.used),
gb_or_unknown(disk.total),
percent_or_unknown(disk_percent(disk.used, disk.total)),
disk.mount_point
))
})
.collect();
let disks = List::new(disk_items)
.block(Block::default().borders(Borders::ALL).title("Disks"))
.style(Style::default().fg(Color::White));
f.render_widget(disks, chunks[1]);
}
#[allow(dead_code)]
fn draw_footer(f: &mut Frame, app: &App, area: Rect) {
if let Some(status_msg) = app.get_status_message() {
let status = Paragraph::new(Line::from(vec![Span::styled(
status_msg,
Style::default()
.fg(Color::Green)
.add_modifier(Modifier::BOLD),
)]))
.block(Block::default().borders(Borders::ALL))
.alignment(Alignment::Center);
f.render_widget(status, area);
} else if app.agent_input_mode {
let input_text = format!("> {}", app.agent_input);
let input = Paragraph::new(Line::from(vec![
Span::styled(
"Agent Query: ",
Style::default()
.fg(Color::Cyan)
.add_modifier(Modifier::BOLD),
),
Span::raw(&input_text),
Span::styled(
"█",
Style::default()
.fg(Color::Cyan)
.add_modifier(Modifier::SLOW_BLINK),
),
]))
.block(Block::default().borders(Borders::ALL))
.alignment(Alignment::Left);
f.render_widget(input, area);
} else {
let help_text = vec![
Span::raw("Press "),
Span::styled("q", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to quit | "),
Span::styled("</", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to switch tabs | "),
Span::styled("r", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to reset graphs | "),
Span::styled("a", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" for agent | "),
Span::styled("F12", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to save config"),
];
let help = Paragraph::new(Line::from(help_text))
.block(Block::default().borders(Borders::ALL))
.alignment(Alignment::Center);
f.render_widget(help, area);
}
}
fn draw_agent(f: &mut Frame, app: &App, area: Rect) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(6), Constraint::Min(0), ])
.split(area);
let info_lines = if let Some(ref agent) = app.agent {
let cache_stats = app.agent_cache_stats().unwrap_or_default();
let model = match &agent.config().backend {
Some(b) => format!("{} via {}", b.model_id, b.backend_type),
None => "none configured (rule-based)".to_string(),
};
vec![
Line::from(vec![Span::styled(
"[AI Agent Active]",
Style::default()
.fg(Color::Cyan)
.add_modifier(Modifier::BOLD),
)]),
Line::from(format!("Model: {} | {}", model, cache_stats)),
Line::from(""),
Line::from(vec![
Span::raw("Press "),
Span::styled("a", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to ask a question | "),
Span::styled("c", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to clear history"),
]),
]
} else {
vec![
Line::from(vec![Span::styled(
"❌ AI Agent Unavailable",
Style::default().fg(Color::Red).add_modifier(Modifier::BOLD),
)]),
Line::from(""),
Line::from("Agent failed to initialize. Check error logs."),
]
};
let info = Paragraph::new(info_lines)
.block(
Block::default()
.borders(Borders::ALL)
.title("AI Agent - Natural Language Queries"),
)
.style(Style::default().fg(Color::White));
f.render_widget(info, chunks[0]);
draw_agent_history(f, app, chunks[1]);
}
fn draw_agent_history(f: &mut Frame, app: &App, area: Rect) {
if app.agent_history.is_empty() {
let help_text = vec![
Line::from(""),
Line::from(vec![Span::styled(
"No queries yet. Try asking:",
Style::default().add_modifier(Modifier::BOLD),
)]),
Line::from(""),
Line::from(" * What's my GPU temperature?"),
Line::from(" * How much power am I using?"),
Line::from(" * Show GPU utilization"),
Line::from(" * Is my system healthy?"),
Line::from(" * Compare GPU temperatures"),
Line::from(" * What's my memory usage?"),
Line::from(""),
Line::from(vec![
Span::raw("Press "),
Span::styled("a", Style::default().add_modifier(Modifier::BOLD)),
Span::raw(" to start asking questions"),
]),
];
let help = Paragraph::new(help_text)
.block(Block::default().borders(Borders::ALL).title("Examples"))
.alignment(Alignment::Left);
f.render_widget(help, area);
} else {
thread_local! {
static CACHE: std::cell::RefCell<(u64, Vec<Line<'static>>)> =
const { std::cell::RefCell::new((u64::MAX, Vec::new())) };
}
let history_paragraph = CACHE.with(|cell| {
let mut c = cell.borrow_mut();
if c.0 != app.agent_history_version {
c.1 = build_agent_history_lines(app);
c.0 = app.agent_history_version;
}
c.1.clone()
});
let history = Paragraph::new(history_paragraph)
.block(Block::default().borders(Borders::ALL).title(format!(
"Conversation History ({} queries)",
app.agent_history.len()
)))
.wrap(ratatui::widgets::Wrap { trim: false });
f.render_widget(history, area);
}
}
fn draw_inference_tab(f: &mut Frame, app: &App, area: Rect) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Percentage(60), Constraint::Percentage(40)])
.split(area);
let states = app.inference_states();
let gpus = app.inference_gpus();
inference_view::draw(f, chunks[0], &states, &gpus);
draw_agent_history(f, app, chunks[1]);
}
fn draw_agents_tab(f: &mut Frame, app: &App, area: Rect) {
let report = match app.agents.as_ref() {
Some(poller) => {
let state = poller.state();
let engine = app
.inference
.as_ref()
.and_then(|p| crate::agents::engine_requests(&p.states()));
crate::agents::report::build(&state, engine, chrono::Utc::now())
}
None => crate::agents::report::Report {
summary: vec!["Agents: the recordings reader is not running".into()],
sections: Vec::new(),
},
};
agents_view::draw(f, area, &report, app.agents_scroll);
}
fn build_agent_history_lines(app: &App) -> Vec<Line<'static>> {
let mut lines: Vec<Line<'static>> = Vec::new();
let total = app.agent_history.len();
for (i, response) in app.agent_history.iter().rev().enumerate() {
let time_str = format!(
"[{}ms{}]",
response.inference_time_ms,
if response.from_cache { ", cached" } else { "" }
);
lines.push(Line::from(vec![
Span::styled(
format!("Q{}: ", total - i),
Style::default()
.fg(Color::Yellow)
.add_modifier(Modifier::BOLD),
),
Span::raw(response.query.clone()),
Span::styled(
format!(" {}", time_str),
Style::default().fg(Color::DarkGray),
),
]));
let mut first = true;
for body_line in response.response.split('\n') {
if first {
lines.push(Line::from(vec![
Span::styled(
"A: ",
Style::default()
.fg(Color::Cyan)
.add_modifier(Modifier::BOLD),
),
Span::styled(body_line.to_string(), Style::default().fg(Color::White)),
]));
first = false;
} else {
lines.push(Line::from(vec![
Span::raw(" "),
Span::styled(body_line.to_string(), Style::default().fg(Color::White)),
]));
}
}
lines.push(Line::from(""));
}
lines
}
fn usage_color(percent: f32) -> Color {
threshold_color(percent)
}
fn draw_peripherals(f: &mut Frame, app: &App, area: Rect) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage(20),
Constraint::Percentage(20),
Constraint::Percentage(20),
Constraint::Percentage(20),
Constraint::Percentage(20),
])
.split(area);
let audio_block = Block::default()
.borders(Borders::ALL)
.title("Audio Devices")
.border_style(Style::default().fg(glances_colors::TITLE));
let audio_para = Paragraph::new(app.peripheral_cache.audio_info.as_str()).block(audio_block);
f.render_widget(audio_para, chunks[0]);
let display_block = Block::default()
.borders(Borders::ALL)
.title("Displays")
.border_style(Style::default().fg(glances_colors::TITLE));
let display_para =
Paragraph::new(app.peripheral_cache.display_info.as_str()).block(display_block);
f.render_widget(display_para, chunks[1]);
let usb_block = Block::default()
.borders(Borders::ALL)
.title("USB Devices")
.border_style(Style::default().fg(glances_colors::TITLE));
let usb_para = Paragraph::new(app.peripheral_cache.usb_info.as_str()).block(usb_block);
f.render_widget(usb_para, chunks[2]);
let bt_block = Block::default()
.borders(Borders::ALL)
.title("Bluetooth")
.border_style(Style::default().fg(glances_colors::TITLE));
let bt_para = Paragraph::new(app.peripheral_cache.bluetooth_info.as_str()).block(bt_block);
f.render_widget(bt_para, chunks[3]);
let battery_block = Block::default()
.borders(Borders::ALL)
.title("Battery / Power")
.border_style(Style::default().fg(glances_colors::TITLE));
let battery_para =
Paragraph::new(app.peripheral_cache.battery_info.as_str()).block(battery_block);
f.render_widget(battery_para, chunks[4]);
}
fn draw_process_detail_overlay(f: &mut Frame, app: &App) {
let area = centered_rect(60, 50, f.area());
let block = Block::default()
.borders(Borders::ALL)
.border_style(Style::default().fg(Color::Rgb(137, 180, 250)))
.title(" Process Detail (Enter/Esc to close) ")
.title_style(
Style::default()
.fg(Color::Rgb(137, 180, 250))
.add_modifier(Modifier::BOLD),
)
.style(Style::default().bg(Color::Rgb(30, 30, 46)));
let inner = block.inner(area);
f.render_widget(ratatui::widgets::Clear, area);
f.render_widget(block, area);
if let Some(process) = app.get_selected_process() {
let lines = vec![
Line::from(vec![
Span::styled("PID: ", Style::default().fg(Color::Rgb(166, 227, 161))),
Span::raw(format!("{}", process.pid)),
]),
Line::from(vec![
Span::styled("Name: ", Style::default().fg(Color::Rgb(166, 227, 161))),
Span::raw(&process.name),
]),
Line::from(vec![
Span::styled("User: ", Style::default().fg(Color::Rgb(166, 227, 161))),
Span::raw(process.user.as_deref().unwrap_or("unknown")),
]),
Line::from(vec![
Span::styled("CPU: ", Style::default().fg(Color::Rgb(166, 227, 161))),
Span::raw(
process
.cpu_percent
.map_or_else(|| "not yet known".to_string(), |c| format!("{c:.1}%")),
),
]),
Line::from(vec![
Span::styled("Memory: ", Style::default().fg(Color::Rgb(166, 227, 161))),
Span::raw(auto_unit(process.memory_bytes)),
]),
Line::from(vec![
Span::styled("State: ", Style::default().fg(Color::Rgb(166, 227, 161))),
Span::raw(format!("{}", process.state)),
]),
Line::from(vec![
Span::styled("Threads: ", Style::default().fg(Color::Rgb(166, 227, 161))),
Span::raw(format!("{}", process.thread_count)),
]),
Line::from(""),
Line::from(vec![
Span::styled(
"GPU Usage: ",
Style::default().fg(Color::Rgb(250, 179, 135)),
),
Span::raw(
process
.gpu_usage_percent
.map(|u| format!("{:.1}%", u))
.unwrap_or_else(|| "-".to_string()),
),
]),
Line::from(vec![
Span::styled(
"GPU Memory: ",
Style::default().fg(Color::Rgb(250, 179, 135)),
),
Span::raw(match process.total_gpu_memory_bytes {
Some(b) if b > 0 => auto_unit(b),
Some(_) => "0".to_string(),
None => "-".to_string(),
}),
]),
Line::from(vec![
Span::styled("Encoder: ", Style::default().fg(Color::Rgb(250, 179, 135))),
Span::raw(
process
.encoder_usage_percent
.map(|u| format!("{:.1}%", u))
.unwrap_or_else(|| "-".to_string()),
),
]),
Line::from(vec![
Span::styled("Decoder: ", Style::default().fg(Color::Rgb(250, 179, 135))),
Span::raw(
process
.decoder_usage_percent
.map(|u| format!("{:.1}%", u))
.unwrap_or_else(|| "-".to_string()),
),
]),
];
let para = Paragraph::new(lines);
f.render_widget(para, inner);
}
}
fn draw_theme_picker_overlay(f: &mut Frame, app: &App) {
use super::app::ColorTheme;
let themes = ColorTheme::all();
let height = (themes.len() + 4) as u16;
let area = centered_rect(40, height.min(20), f.area());
let block = Block::default()
.borders(Borders::ALL)
.border_style(Style::default().fg(Color::Rgb(137, 180, 250)))
.title(" Select Theme (Enter to apply, Esc to cancel) ")
.title_style(
Style::default()
.fg(Color::Rgb(137, 180, 250))
.add_modifier(Modifier::BOLD),
)
.style(Style::default().bg(Color::Rgb(30, 30, 46)));
let inner = block.inner(area);
f.render_widget(ratatui::widgets::Clear, area);
f.render_widget(block, area);
let items: Vec<ListItem> = themes
.iter()
.enumerate()
.map(|(idx, theme)| {
let is_selected = idx == app.selected_theme_idx;
let is_current = *theme == app.color_theme;
let name = if is_current {
format!("{} (current)", theme.name())
} else {
theme.name().to_string()
};
let style = if is_selected {
Style::default()
.bg(Color::Rgb(69, 71, 90))
.fg(Color::Rgb(205, 214, 244))
} else {
Style::default().fg(Color::Rgb(166, 173, 200))
};
ListItem::new(name).style(style)
})
.collect();
let list = List::new(items);
f.render_widget(list, inner);
}
fn centered_rect(percent_x: u16, percent_y: u16, r: Rect) -> Rect {
let popup_layout = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage((100 - percent_y) / 2),
Constraint::Percentage(percent_y),
Constraint::Percentage((100 - percent_y) / 2),
])
.split(r);
Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Percentage((100 - percent_x) / 2),
Constraint::Percentage(percent_x),
Constraint::Percentage((100 - percent_x) / 2),
])
.split(popup_layout[1])[1]
}
fn draw_profiles_tab(f: &mut Frame, app: &App, area: Rect) {
use crate::profile::Subsystem;
if app.profile_show_deviations {
draw_profile_deviations_overlay(f, app, area);
return;
}
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Length(3), Constraint::Min(0)])
.split(area);
let titles: Vec<&str> = Subsystem::ALL.iter().map(|s| s.as_str()).collect();
let sub_tabs = Tabs::new(titles)
.block(
Block::default()
.borders(Borders::ALL)
.title(" Profile Inspector — [1-5] subsystem · [r] refresh · [d] deviations · [↑↓ PgUp/PgDn] scroll "),
)
.select(app.profile_subsystem_idx)
.highlight_style(
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD),
);
f.render_widget(sub_tabs, chunks[0]);
let Some(snapshot) = app.profile_snapshot.as_ref() else {
let msg = Paragraph::new(vec![
Line::from(Span::styled(
"Loading hardware profile snapshot…",
Style::default().fg(glances_colors::TITLE),
)),
Line::from(""),
Line::from("Press 'r' to fetch — initial NVML/registry/SMBIOS reads take a moment."),
])
.block(Block::default().borders(Borders::ALL));
f.render_widget(msg, chunks[1]);
return;
};
let sub = Subsystem::ALL
.get(app.profile_subsystem_idx)
.copied()
.unwrap_or(Subsystem::Gpu);
let read_error = snapshot.errors.get(&sub);
let groups = snapshot.providers.get(&sub).cloned().unwrap_or_default();
let mut lines: Vec<Line> = Vec::new();
let header = match read_error {
Some(reason) => format!(
"not read: {} · captured @ ts={}",
reason, snapshot.timestamp
),
None => format!(
"{} group(s) · {} setting(s) · captured @ ts={}",
groups.len(),
groups.iter().map(|g| g.settings.len()).sum::<usize>(),
snapshot.timestamp
),
};
lines.push(Line::from(Span::styled(
header,
Style::default().fg(glances_colors::CAREFUL),
)));
lines.push(Line::from(""));
for group in &groups {
lines.push(Line::from(vec![
Span::styled(
"▸ ",
Style::default()
.fg(glances_colors::TITLE)
.add_modifier(Modifier::BOLD),
),
Span::styled(
group.device.clone(),
Style::default().add_modifier(Modifier::BOLD),
),
Span::raw(" "),
Span::styled(
group.display_name.clone(),
Style::default().fg(glances_colors::CAREFUL),
),
]));
lines.push(Line::from(vec![
Span::styled(" source: ", Style::default().fg(Color::DarkGray)),
Span::styled(
group.source.clone(),
Style::default()
.fg(Color::DarkGray)
.add_modifier(Modifier::ITALIC),
),
]));
for s in &group.settings {
let risk_color = match s.risk {
crate::profile::SettingRisk::Informational => Color::Reset,
crate::profile::SettingRisk::Safe => glances_colors::OK,
crate::profile::SettingRisk::Moderate => glances_colors::WARNING,
crate::profile::SettingRisk::Dangerous => glances_colors::CRITICAL,
};
let unit = s
.unit
.as_deref()
.map(|u| format!(" {}", u))
.unwrap_or_default();
let value_str = format!("{}{}", s.value, unit);
lines.push(Line::from(vec![
Span::raw(" "),
Span::styled(
format!("{:<28}", trunc(&s.display_name, 28)),
Style::default().fg(risk_color),
),
Span::raw(" = "),
Span::styled(value_str, Style::default().add_modifier(Modifier::BOLD)),
]));
}
for n in &group.notes {
lines.push(Line::from(vec![
Span::raw(" "),
Span::styled("• ", Style::default().fg(Color::DarkGray)),
Span::styled(n.clone(), Style::default().fg(Color::DarkGray)),
]));
}
lines.push(Line::from(""));
}
if groups.is_empty() {
lines.push(Line::from(Span::styled(
"(no profile data for this subsystem on this platform)",
Style::default().fg(Color::DarkGray),
)));
}
let paragraph = Paragraph::new(lines)
.block(Block::default().borders(Borders::ALL).title(format!(
" {} — Hardware Profile Inspector ",
sub.as_str().to_uppercase()
)))
.scroll((app.profile_scroll, 0));
f.render_widget(paragraph, chunks[1]);
}
fn trunc(s: &str, n: usize) -> String {
if s.chars().count() <= n {
s.to_string()
} else {
let mut out: String = s.chars().take(n.saturating_sub(1)).collect();
out.push('…');
out
}
}
fn draw_profile_deviations_overlay(f: &mut Frame, app: &App, area: Rect) {
let chunks = Layout::default()
.direction(Direction::Vertical)
.constraints([Constraint::Percentage(60), Constraint::Percentage(40)])
.split(area);
let mut dev_lines: Vec<Line> = Vec::new();
dev_lines.push(Line::from(Span::styled(
"press [d] to return to profile view",
Style::default().fg(Color::DarkGray),
)));
dev_lines.push(Line::from(""));
if let Some(snapshot) = app.profile_snapshot.as_ref() {
let devs = crate::profile::deviation::deviations_from_default(snapshot);
if devs.is_empty() {
dev_lines.push(Line::from(Span::styled(
"All settings with a declared default are at their default value.",
Style::default().fg(glances_colors::OK),
)));
} else {
dev_lines.push(Line::from(Span::styled(
format!("{} deviation(s):", devs.len()),
Style::default()
.fg(glances_colors::WARNING)
.add_modifier(Modifier::BOLD),
)));
dev_lines.push(Line::from(""));
for d in devs {
let risk_color = match d.risk {
crate::profile::SettingRisk::Dangerous => glances_colors::CRITICAL,
crate::profile::SettingRisk::Moderate => glances_colors::WARNING,
crate::profile::SettingRisk::Safe => glances_colors::OK,
crate::profile::SettingRisk::Informational => Color::DarkGray,
};
dev_lines.push(Line::from(vec![
Span::styled(
format!(" [{:?}] ", d.risk),
Style::default().fg(risk_color),
),
Span::styled(
format!("[{}] ", d.subsystem.as_str()),
Style::default().fg(glances_colors::TITLE),
),
Span::raw(format!("{} :: ", d.device)),
Span::styled(
d.display_name.clone(),
Style::default().add_modifier(Modifier::BOLD),
),
]));
dev_lines.push(Line::from(vec![
Span::raw(" default: "),
Span::styled(d.default.to_string(), Style::default().fg(Color::DarkGray)),
Span::raw(" current: "),
Span::styled(
d.current.to_string(),
Style::default().fg(risk_color).add_modifier(Modifier::BOLD),
),
]));
}
}
} else {
dev_lines.push(Line::from(Span::styled(
"(no snapshot — return to profile view and press [r] to refresh)",
Style::default().fg(Color::DarkGray),
)));
}
let dev_para = Paragraph::new(dev_lines).block(
Block::default()
.borders(Borders::ALL)
.title(" Deviations from default "),
);
f.render_widget(dev_para, chunks[0]);
let audit_path = crate::profile::apply::audit_log_path();
let content = std::fs::read_to_string(&audit_path).unwrap_or_default();
let all_lines: Vec<&str> = content.lines().collect();
let tail_n = 8usize.min(all_lines.len());
let tail = if all_lines.len() > tail_n {
&all_lines[all_lines.len() - tail_n..]
} else {
&all_lines[..]
};
let mut audit_lines: Vec<Line> = Vec::new();
audit_lines.push(Line::from(Span::styled(
format!("source: {}", audit_path.display()),
Style::default().fg(Color::DarkGray),
)));
audit_lines.push(Line::from(""));
if tail.is_empty() {
audit_lines.push(Line::from(Span::styled(
"(no audit entries)",
Style::default().fg(Color::DarkGray),
)));
} else {
for line in tail {
if let Ok(o) = serde_json::from_str::<crate::profile::apply::ApplyOutcome>(line) {
let (status_str, status_color) = match o.status {
crate::profile::apply::ApplyStatus::Applied => ("applied", glances_colors::OK),
crate::profile::apply::ApplyStatus::Refused => {
("refused", glances_colors::CRITICAL)
}
crate::profile::apply::ApplyStatus::Failed => {
("failed", glances_colors::CRITICAL)
}
crate::profile::apply::ApplyStatus::NotWritable => {
("not-writable", glances_colors::WARNING)
}
crate::profile::apply::ApplyStatus::NeedsConfirm => {
("needs-confirm", glances_colors::WARNING)
}
};
audit_lines.push(Line::from(vec![
Span::styled(
format!(" [{}] ", o.timestamp),
Style::default().fg(Color::DarkGray),
),
Span::styled(
format!("{:<13}", status_str),
Style::default().fg(status_color),
),
Span::raw(" "),
Span::styled(o.setting_id, Style::default().add_modifier(Modifier::BOLD)),
Span::raw(format!(" = {}", o.requested)),
]));
}
}
}
let audit_para = Paragraph::new(audit_lines).block(
Block::default()
.borders(Borders::ALL)
.title(" Apply audit log (tail) "),
);
f.render_widget(audit_para, chunks[1]);
}
fn auto_unit_opt(bytes: Option<u64>) -> String {
bytes.map_or_else(|| "-".to_string(), auto_unit)
}
fn pct_opt(pct: Option<f64>) -> String {
pct.map_or_else(|| "-".to_string(), |p| format!("{p:.0}%"))
}
fn mhz_opt(mhz: Option<u32>) -> String {
mhz.map_or_else(|| "- MHz".to_string(), |m| format!("{m} MHz"))
}
fn celsius_opt(c: Option<f32>) -> String {
c.map_or_else(|| "-°C".to_string(), |c| format!("{c:.0}°C"))
}
fn watts_opt(draw: Option<f32>, limit: Option<f32>) -> String {
let w = |v: Option<f32>| v.map_or_else(|| "-".to_string(), |v| format!("{v:.0}"));
format!("{}/{}W", w(draw), w(limit))
}
fn uptime_opt(uptime: Option<std::time::Duration>) -> String {
uptime.map_or_else(
|| "--".to_string(),
|d| {
let secs = d.as_secs();
format!(
"{}d {}h {}m",
secs / 86400,
(secs % 86400) / 3600,
(secs % 3600) / 60
)
},
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unread_gpu_figures_are_dashes_and_percentages_print() {
assert_eq!(mhz_opt(None), "- MHz");
assert_eq!(mhz_opt(Some(1860)), "1860 MHz");
assert_eq!(celsius_opt(None), "-°C");
assert_eq!(celsius_opt(Some(47.4)), "47°C");
assert_eq!(watts_opt(None, None), "-/-W");
assert_eq!(watts_opt(Some(77.2), Some(450.0)), "77/450W");
assert_eq!(format!("({})", pct_opt(Some(14.2))), "(14%)");
}
#[test]
fn unread_uptime_is_dashes_not_zero_days() {
use std::time::Duration;
assert_eq!(uptime_opt(None), "--");
assert_eq!(uptime_opt(Some(Duration::from_secs(0))), "0d 0h 0m");
assert_eq!(uptime_opt(Some(Duration::from_secs(90_061))), "1d 1h 1m");
}
#[test]
fn absent_readings_render_as_nothing_not_as_zero() {
assert_eq!(opt_mhz(None, " @ "), "");
assert_eq!(opt_celsius(None, " │ "), "");
assert_eq!(opt_mhz(Some(4400), " @ "), " @ 4400 MHz");
assert_eq!(opt_celsius(Some(61.4), " │ "), " │ 61°C");
assert_eq!(opt_mhz(Some(0), " @ "), " @ 0 MHz");
assert_eq!(opt_celsius(Some(0.0), " │ "), " │ 0°C");
}
#[test]
fn separators_do_not_dangle_when_a_reading_is_absent() {
let label = format!(
"{} cores{}{}",
24,
opt_mhz(None, " @ "),
opt_celsius(None, " │ ")
);
assert_eq!(label, "24 cores");
}
}