corelens 0.1.0

Linux TUI for CPU topology, local AI workloads, and GPU metrics
Documentation
use crate::{app::App, model::cpu::CoreKind, ui::cpu_matrix_grid::display_label};
use ratatui::{
    prelude::*,
    widgets::{Block, Borders, Paragraph, Wrap},
};

pub fn render(
    frame: &mut Frame<'_>,
    area: Rect,
    app: &App,
    core_index: usize,
    dimension: usize,
    selected: bool,
) {
    let Some(core) = app.cpu.cores.get(core_index) else {
        return;
    };
    let cpus: Vec<_> = core
        .logical_cpus
        .iter()
        .filter_map(|id| app.cpu.cpus.iter().find(|cpu| cpu.logical_id == *id))
        .collect();
    let kind = cpus
        .first()
        .map(|cpu| cpu.core_kind)
        .unwrap_or(CoreKind::Unknown);
    let label = display_label(app, core_index);
    let util = average(&cpus);
    let mut lines = vec![Line::from(format!(
        "{label} {:02.0}%",
        util.unwrap_or_default()
    ))];
    let fill = filled_cells(util, dimension * dimension);
    let glyph = filled_glyph(kind, util.unwrap_or_default());
    let style = match kind {
        CoreKind::Performance => Style::default().fg(Color::Yellow),
        CoreKind::Efficiency | CoreKind::LowPowerEfficiency => Style::default().fg(Color::Cyan),
        _ => Style::default(),
    };
    let cells = cell_order(dimension);
    for row in 0..dimension {
        let mut spans = Vec::with_capacity(dimension);
        for column in 0..dimension {
            let index = row * dimension + column;
            let filled = cells
                .iter()
                .position(|cell| *cell == index)
                .is_some_and(|position| position < fill);
            spans.push(Span::styled(
                format!("{} ", if filled { glyph } else { '░' }),
                if filled { style } else { Style::default() },
            ));
        }
        lines.push(Line::from(spans));
    }
    let frequency = cpus
        .iter()
        .filter_map(|cpu| cpu.current_frequency_khz.or(cpu.max_frequency_khz))
        .max()
        .map(|value| format!("{:.1}G", value as f64 / 1_000_000.0))
        .unwrap_or_else(|| "--".into());
    lines.push(Line::from(format!("{frequency} · {}T", cpus.len())));
    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(if selected {
            style.add_modifier(Modifier::BOLD)
        } else {
            style
        });
    frame.render_widget(
        Paragraph::new(Text::from(lines))
            .block(block)
            .wrap(Wrap { trim: true }),
        area,
    );
}

fn average(cpus: &[&crate::model::cpu::LogicalCpu]) -> Option<f64> {
    let values: Vec<f64> = cpus.iter().filter_map(|cpu| cpu.utilization).collect();
    (!values.is_empty()).then(|| values.iter().sum::<f64>() / values.len() as f64)
}
fn filled_glyph(kind: CoreKind, utilization: f64) -> char {
    let shade = if utilization < 25.0 {
        '▪'
    } else if utilization < 50.0 {
        '▒'
    } else if utilization < 75.0 {
        '▓'
    } else {
        '█'
    };
    match (kind, shade) {
        (CoreKind::Efficiency | CoreKind::LowPowerEfficiency, '█') => '▓',
        _ => shade,
    }
}
fn filled_cells(util: Option<f64>, total: usize) -> usize {
    ((util.unwrap_or_default().clamp(0.0, 100.0) / 100.0) * total as f64).round() as usize
}
fn cell_order(dimension: usize) -> Vec<usize> {
    let center = (dimension as f64 - 1.0) / 2.0;
    let mut cells: Vec<(usize, f64)> = (0..dimension * dimension)
        .map(|index| {
            let row = index / dimension;
            let column = index % dimension;
            let distance =
                ((row as f64 - center).powi(2) + (column as f64 - center).powi(2)).sqrt();
            (index, distance)
        })
        .collect();
    cells.sort_by(|a, b| a.1.total_cmp(&b.1));
    cells.into_iter().map(|(index, _)| index).collect()
}