Skip to content

Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇

10.4 KB
Raw Blame
// ©AngelaMos | 2026
// overview.rs

use lisdex_monitor::snapshot::{CurvePoint, Snapshot, Totals};
use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Style};
use ratatui::symbols::Marker;
use ratatui::text::{Line, Span};
use ratatui::widgets::{
    Axis, Block, BorderType, Chart, Dataset, GraphType, LineGauge, Paragraph, Sparkline,
};

use crate::app::App;
use crate::format;
use crate::theme;

const SPARK_SAMPLES: usize = 120;
const CHART_BANDS: usize = theme::RAMP.len();
const MIN_BAND_POINTS: usize = 2;
const RIGHT_COLUMN_WIDTH: u16 = 32;
const SPARK_HEIGHT: u16 = 6;
const GAUGE_HEIGHT: u16 = 3;

pub fn render(frame: &mut Frame, area: Rect, app: &App) {
    let [top, gauge] =
        Layout::vertical([Constraint::Min(6), Constraint::Length(GAUGE_HEIGHT)]).areas(area);
    let [left, right] =
        Layout::horizontal([Constraint::Min(24), Constraint::Length(RIGHT_COLUMN_WIDTH)])
            .areas(top);
    let [spark, telemetry] =
        Layout::vertical([Constraint::Length(SPARK_HEIGHT), Constraint::Min(0)]).areas(right);

    coverage(frame, left, app.snapshot());
    exec_rate(frame, spark, app.snapshot());
    numbers(frame, telemetry, app.snapshot());
    coverage_gauge(frame, gauge, app.snapshot());
}

#[must_use]
pub fn panel(title: &str, accent: Color) -> Block<'static> {
    Block::bordered()
        .border_type(BorderType::Rounded)
        .border_style(theme::border())
        .title_top(Line::from(Span::styled(
            format!(" {title} "),
            theme::title(accent),
        )))
        .style(theme::panel())
}

pub fn placeholder(frame: &mut Frame, area: Rect, title: &str, accent: Color, message: &str) {
    frame.render_widget(
        Paragraph::new(Line::from(Span::styled(message.to_owned(), theme::dim())))
            .block(panel(title, accent)),
        area,
    );
}

fn coverage(frame: &mut Frame, area: Rect, snapshot: &Snapshot) {
    let curve = snapshot.curve();
    if curve.len() < MIN_BAND_POINTS {
        placeholder(
            frame,
            area,
            "COVERAGE",
            theme::NEON_CYAN,
            "waiting for the campaign to write its first samples",
        );
        return;
    }

    let points = plot_points(curve);
    let (x_max, y_min, y_max) = bounds(
        &points,
        as_f64(snapshot.lowest_edges()),
        as_f64(snapshot.peak_edges()),
    );
    let bands = band_ranges(points.len());
    let datasets: Vec<Dataset<'_>> = bands
        .iter()
        .enumerate()
        .map(|(index, range)| {
            Dataset::default()
                .marker(Marker::Braille)
                .graph_type(GraphType::Line)
                .style(Style::default().fg(theme::ramp_at(index)))
                .data(&points[range.clone()])
        })
        .collect();

    let title = snapshot
        .curve_instance()
        .map_or_else(|| "COVERAGE".to_owned(), |name| format!("COVERAGE  {name}"));

    let chart = Chart::new(datasets)
        .block(panel(&title, theme::NEON_CYAN))
        .x_axis(
            Axis::default()
                .style(theme::dim())
                .bounds([0.0, x_max])
                .labels(vec![
                    Span::styled("0s", theme::dim()),
                    Span::styled(format::duration(snapshot.elapsed_secs()), theme::label()),
                ]),
        )
        .y_axis(
            Axis::default()
                .style(theme::dim())
                .bounds([y_min, y_max])
                .labels(vec![
                    Span::styled(format::count(format::bar_value(y_min)), theme::dim()),
                    Span::styled(
                        format::count(format::bar_value(y_max)),
                        theme::value(theme::ACID_GREEN),
                    ),
                ]),
        );
    frame.render_widget(chart, area);
}

fn plot_points(curve: &[CurvePoint]) -> Vec<(f64, f64)> {
    curve
        .iter()
        .map(|point| (as_f64(point.secs), as_f64(point.edges)))
        .collect()
}

fn bounds(points: &[(f64, f64)], y_min: f64, peak: f64) -> (f64, f64, f64) {
    let x_max = points.last().map_or(1.0, |point| point.0).max(1.0);
    let y_max = if (peak - y_min).abs() < 1.0 {
        y_min + 1.0
    } else {
        peak
    };
    (x_max, y_min, y_max)
}

fn band_ranges(len: usize) -> Vec<std::ops::Range<usize>> {
    if len < CHART_BANDS * MIN_BAND_POINTS {
        return std::iter::once(0..len).collect();
    }
    let step = len / CHART_BANDS;
    (0..CHART_BANDS)
        .map(|index| {
            let start = index * step;
            let end = if index == CHART_BANDS - 1 {
                len
            } else {
                (start + step + 1).min(len)
            };
            start..end
        })
        .collect()
}

fn exec_rate(frame: &mut Frame, area: Rect, snapshot: &Snapshot) {
    let curve = snapshot.curve();
    if curve.is_empty() {
        placeholder(
            frame,
            area,
            "EXEC RATE",
            theme::NEON_MAGENTA,
            "no samples yet",
        );
        return;
    }
    let data: Vec<u64> = curve
        .iter()
        .rev()
        .take(SPARK_SAMPLES)
        .map(|point| format::bar_value(point.execs_per_sec))
        .collect::<Vec<_>>()
        .into_iter()
        .rev()
        .collect();
    let latest = snapshot.latest_execs_per_sec().unwrap_or(0.0);
    let widget = Sparkline::default()
        .block(panel(
            &format!("EXEC RATE  {}", format::rate(latest)),
            theme::NEON_MAGENTA,
        ))
        .style(Style::default().fg(theme::NEON_MAGENTA))
        .data(data);
    frame.render_widget(widget, area);
}

fn numbers(frame: &mut Frame, area: Rect, snapshot: &Snapshot) {
    let totals = snapshot.totals();
    let lines = vec![
        stat(
            "execs",
            &totals.map_or_else(|| "-".to_owned(), |t| format::count(t.execs_done)),
            theme::INK,
        ),
        stat(
            "combined rate",
            &totals.map_or_else(|| "-".to_owned(), |t| format::rate(t.execs_per_sec)),
            theme::NEON_MAGENTA,
        ),
        stat(
            "corpus",
            &snapshot
                .latest_corpus()
                .map_or_else(|| "-".to_owned(), format::count),
            theme::INK,
        ),
        stat(
            "peak edges",
            &format::count(snapshot.peak_edges()),
            theme::NEON_CYAN,
        ),
        stat(
            "map density",
            &totals.map_or_else(|| "-".to_owned(), |t| format::density(t.map_density_pct)),
            theme::NEON_BLUE,
        ),
        stat(
            "saved crashes",
            &totals.map_or_else(|| "-".to_owned(), |t| format::count(t.saved_crashes)),
            theme::AMBER,
        ),
        stat(
            "distinct bugs",
            &snapshot.distinct_bugs().to_string(),
            theme::HOT_RED,
        ),
        stat(
            "unkeyed",
            &snapshot.unkeyed_crashes().to_string(),
            theme::NEON_VIOLET,
        ),
        stat(
            "instances",
            &snapshot.instances().len().to_string(),
            theme::ACID_GREEN,
        ),
    ];
    frame.render_widget(
        Paragraph::new(lines).block(panel("TELEMETRY", theme::NEON_VIOLET)),
        area,
    );
}

fn stat(name: &str, value: &str, accent: Color) -> Line<'static> {
    Line::from(vec![
        Span::styled(format!("{name:<14}"), theme::label()),
        Span::styled(value.to_owned(), theme::value(accent)),
    ])
}

fn coverage_gauge(frame: &mut Frame, area: Rect, snapshot: &Snapshot) {
    let Some(totals) = snapshot.totals() else {
        placeholder(
            frame,
            area,
            "EDGE COVERAGE",
            theme::ACID_GREEN,
            "no instance has reported a coverage map",
        );
        return;
    };
    let widget = LineGauge::default()
        .block(panel(&gauge_title(totals), theme::ACID_GREEN))
        .filled_style(Style::default().fg(theme::ACID_GREEN))
        .unfilled_style(Style::default().fg(theme::EDGE))
        .label(Span::styled(
            format::percent(totals.edge_ratio()),
            theme::value(theme::ACID_GREEN),
        ))
        .ratio(totals.edge_ratio());
    frame.render_widget(widget, area);
}

fn gauge_title(totals: &Totals) -> String {
    format!(
        "EDGE COVERAGE  {} / {}",
        format::count(totals.edges_found),
        format::count(totals.total_edges)
    )
}

#[expect(clippy::cast_precision_loss)]
fn as_f64(value: u64) -> f64 {
    value as f64
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_short_curve_is_drawn_as_one_band_rather_than_six_empty_ones() {
        assert_eq!(band_ranges(4), vec![0..4]);
        assert_eq!(band_ranges(0), vec![0..0]);
    }

    #[test]
    fn bands_cover_the_whole_curve_and_overlap_so_the_line_never_breaks() {
        let len = 120;
        let bands = band_ranges(len);
        assert_eq!(bands.len(), CHART_BANDS);
        assert_eq!(bands[0].start, 0);
        assert_eq!(bands[bands.len() - 1].end, len);
        for pair in bands.windows(2) {
            assert!(
                pair[0].end > pair[1].start,
                "adjacent colour bands must share a point or the gradient line renders with gaps at every seam"
            );
        }
    }

    #[test]
    fn every_band_is_a_valid_slice_of_the_curve() {
        for len in [12, 13, 61, 107, 601] {
            for range in band_ranges(len) {
                assert!(range.start <= range.end);
                assert!(range.end <= len, "a band ran past the end of the curve");
            }
        }
    }

    #[test]
    fn a_flat_curve_still_produces_a_drawable_y_range() {
        let points = vec![(0.0, 500.0), (10.0, 500.0)];
        let (x_max, y_min, y_max) = bounds(&points, 500.0, 500.0);
        assert!(x_max > 0.0);
        assert!(
            y_max > y_min,
            "a zero-height y axis makes ratatui divide by the range and render nothing"
        );
    }

    #[test]
    fn the_axis_uses_the_range_the_model_measured_rather_than_rescanning_the_curve() {
        let points = vec![(0.0, 100.0), (5.0, 900.0), (9.0, 400.0)];
        let (x_max, y_min, y_max) = bounds(&points, 100.0, 900.0);
        assert!((x_max - 9.0).abs() < f64::EPSILON);
        assert!((y_min - 100.0).abs() < f64::EPSILON);
        assert!(
            (y_max - 900.0).abs() < f64::EPSILON,
            "the top axis label is the campaign's peak coverage, and it must be the same number the telemetry panel prints"
        );
    }
}