Skip to content

Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.

14.9 KB
Raw Blame
//! Settings → Performance → Process Viewer: what RustCord is using right
//! now. Its own process and the helpers it started (the embedded browser
//! behind the login page and embed players), with memory, processor use and
//! threads for each, the last minute as graphs, and a button that hands
//! unused memory back to the system.
//!
//! Nothing is sampled unless the page is open; then once a second.

use std::collections::{HashMap, VecDeque};
use std::time::{Duration, Instant};

use crate::app::RustCord;
use crate::diagnostics::ProcessInfo;
use crate::style::{medium, overlay, Theme};
use eframe::egui::{self, pos2, vec2, Align2, Color32, FontFamily, FontId, Rect, RichText, Sense, Shape, Stroke, Ui};

/// How much history the graphs show: a sample a second.
const HISTORY: usize = 60;
const SAMPLE_EVERY: Duration = Duration::from_secs(1);

/// The system's name and its own process monitor, for the explanations.
const SYSTEM: &str = if cfg!(windows) {
    "Windows"
} else if cfg!(target_os = "macos") {
    "macOS"
} else {
    "the system"
};
const MONITOR: &str = if cfg!(windows) {
    "Task Manager"
} else if cfg!(target_os = "macos") {
    "Activity Monitor"
} else {
    "your system monitor"
};

fn strong(size: f32) -> FontId {
    FontId::new(size, FontFamily::Name(crate::style::BOLD.into()))
}

#[derive(Default)]
pub struct ProcessViewer {
    /// RustCord first, then its helpers.
    processes: Vec<ProcessInfo>,
    /// Each process's share of the whole processor since the last sample, 0–100.
    cpu: HashMap<u32, f32>,
    sampled: Option<Instant>,
    /// Processor seconds per process at the last sample.
    cpu_before: HashMap<u32, f64>,
    /// Totals over the last minute: memory in MB, processor in percent.
    memory_history: VecDeque<f32>,
    cpu_history: VecDeque<f32>,
    /// What "Free unused memory" last gave back, and when.
    freed: Option<(i64, Instant)>,
}

/// A process's memory as Task Manager counts it (private pages in RAM), or
/// all of its pages in RAM where Windows wouldn't tell them apart.
fn memory(p: &ProcessInfo) -> u64 {
    p.private_working_set.unwrap_or(p.working_set)
}

fn mb(bytes: u64) -> String {
    let v = bytes as f64 / (1024.0 * 1024.0);
    if v >= 100.0 {
        format!("{v:.0} MB")
    } else {
        format!("{v:.1} MB")
    }
}

fn percent(v: f32) -> String {
    if v < 0.05 {
        "0%".into()
    } else if v < 10.0 {
        format!("{v:.1}%")
    } else {
        format!("{v:.0}%")
    }
}

/// What a helper process is, from its program's name.
fn describe(p: &ProcessInfo, main: bool) -> String {
    if main {
        return "RustCord".into();
    }
    match p.name.to_ascii_lowercase().as_str() {
        "msedgewebview2.exe" => "Embedded browser (WebView2)".into(),
        "rustcord.exe" => "RustCord helper".into(),
        _ => p.name.clone(),
    }
}

impl ProcessViewer {
    fn sample(&mut self) {
        let now = Instant::now();
        let elapsed = self.sampled.map(|t| now.duration_since(t).as_secs_f64());
        let cores = std::thread::available_parallelism().map_or(1, |n| n.get()) as f64;
        let processes = crate::diagnostics::process_tree();
        let mut cpu = HashMap::new();
        if let Some(dt) = elapsed.filter(|dt| *dt > 0.05) {
            for p in &processes {
                if let Some(before) = self.cpu_before.get(&p.pid) {
                    cpu.insert(p.pid, ((p.cpu_seconds - before).max(0.0) / dt / cores * 100.0) as f32);
                }
            }
        }
        self.cpu_before = processes.iter().map(|p| (p.pid, p.cpu_seconds)).collect();
        self.cpu = cpu;
        self.sampled = Some(now);
        for (history, value) in [
            (&mut self.memory_history, processes.iter().map(memory).sum::<u64>() as f32 / (1024.0 * 1024.0)),
            (&mut self.cpu_history, self.cpu.values().sum::<f32>()),
        ] {
            history.push_back(value);
            while history.len() > HISTORY {
                history.pop_front();
            }
        }
        self.processes = processes;
    }
}

/// A figure with its label under it, in a tile.
fn tile(ui: &mut Ui, t: &Theme, rect: Rect, value: &str, label: &str, hint: &str) {
    ui.painter().rect(rect, 8.0, overlay(0.06), Stroke::new(1.0_f32, t.border_subtle));
    ui.painter().text(pos2(rect.left() + 14.0, rect.top() + 26.0), Align2::LEFT_CENTER, value, strong(22.0), t.header_primary);
    ui.painter().text(pos2(rect.left() + 14.0, rect.top() + 52.0), Align2::LEFT_CENTER, label, medium(13.0), t.text_muted);
    ui.interact(rect, ui.id().with(("pv_tile", label)), Sense::hover()).on_hover_text(hint);
}

/// The last minute of `values` as a filled line, newest on the right, the
/// scale's top (`ceiling`) labelled.
fn graph(ui: &mut Ui, t: &Theme, rect: Rect, title: &str, values: &VecDeque<f32>, ceiling: f32, top_label: &str, color: Color32) {
    ui.painter().rect(rect, 8.0, overlay(0.06), Stroke::new(1.0_f32, t.border_subtle));
    ui.painter().text(pos2(rect.left() + 12.0, rect.top() + 16.0), Align2::LEFT_CENTER, title, medium(13.0), t.text_muted);
    ui.painter().text(pos2(rect.right() - 12.0, rect.top() + 16.0), Align2::RIGHT_CENTER, top_label, FontId::proportional(12.0), t.text_muted);
    let plot = Rect::from_min_max(pos2(rect.left() + 12.0, rect.top() + 30.0), pos2(rect.right() - 12.0, rect.bottom() - 10.0));
    ui.painter().hline(plot.x_range(), plot.bottom(), Stroke::new(1.0_f32, t.border_subtle));
    if values.len() < 2 {
        return;
    }
    let step = plot.width() / (HISTORY - 1) as f32;
    let first = plot.right() - step * (values.len() - 1) as f32;
    let points: Vec<egui::Pos2> = values
        .iter()
        .enumerate()
        .map(|(i, v)| pos2(first + step * i as f32, plot.bottom() - (v / ceiling.max(0.001)).clamp(0.0, 1.0) * plot.height()))
        .collect();
    // The area under the line, a strip at a time (each strip is convex).
    let fill = color.gamma_multiply(0.18);
    for pair in points.windows(2) {
        ui.painter().add(Shape::convex_polygon(vec![pair[0], pair[1], pos2(pair[1].x, plot.bottom()), pos2(pair[0].x, plot.bottom())], fill, Stroke::NONE));
    }
    ui.painter().add(Shape::line(points, Stroke::new(1.5_f32, color)));
}

/// A round figure a little above `peak`, so the line doesn't hug the top.
fn ceiling_for(peak: f32, steps: &[f32]) -> f32 {
    steps.iter().copied().find(|s| *s >= peak * 1.15).unwrap_or_else(|| (peak * 1.25 / 100.0).ceil() * 100.0)
}

impl RustCord {
    pub(super) fn process_viewer_tab(&mut self, ui: &mut Ui, t: &Theme) {
        // A fresh sample every second while the page is open.
        if self.process_viewer.sampled.is_none_or(|at| at.elapsed() >= SAMPLE_EVERY) {
            self.process_viewer.sample();
        }
        ui.ctx().request_repaint_after(SAMPLE_EVERY);
        let pv = &self.process_viewer;

        ui.label(RichText::new("Process Viewer").font(strong(20.0)).color(t.header_primary));
        ui.add_space(4.0);
        ui.add(egui::Label::new(RichText::new("What RustCord is using right now: its own process and any helpers it has started. Updated every second while this page is open.").size(14.0).color(t.text_muted)).wrap());
        ui.add_space(16.0);

        let total_memory: u64 = pv.processes.iter().map(memory).sum();
        let total_in_ram: u64 = pv.processes.iter().map(|p| p.working_set).sum();
        let total_cpu: f32 = pv.cpu.values().sum();
        let threads: u32 = pv.processes.iter().map(|p| p.threads).sum();

        // ---- the four figures ----
        let width = ui.available_width();
        let gap = 12.0;
        let (row, _) = ui.allocate_exact_size(vec2(width, 72.0), Sense::hover());
        let w = (width - gap * 3.0) / 4.0;
        let tiles = [
            (mb(total_memory), "Memory", format!("RAM only RustCord is using. This is the figure {MONITOR} shows.")),
            (mb(total_in_ram), "In RAM, with shared", format!("Everything of RustCord's that is in RAM, including program files and fonts that {SYSTEM} shares with other apps.")),
            (percent(total_cpu), "Processor", "Share of the whole processor used over the last second.".to_string()),
            (threads.to_string(), "Threads", "Threads across RustCord and its helpers.".to_string()),
        ];
        for (i, (value, label, hint)) in tiles.iter().enumerate() {
            let r = Rect::from_min_size(pos2(row.left() + (w + gap) * i as f32, row.top()), vec2(w, 72.0));
            tile(ui, t, r, value, label, hint);
        }
        ui.add_space(12.0);

        // ---- the last minute ----
        let (row, _) = ui.allocate_exact_size(vec2(width, 120.0), Sense::hover());
        let w = (width - gap) / 2.0;
        let peak_memory = pv.memory_history.iter().copied().fold(0.0f32, f32::max);
        let memory_top = ceiling_for(peak_memory, &[50.0, 100.0, 150.0, 200.0, 300.0, 400.0, 600.0, 800.0, 1200.0, 1600.0]);
        let peak_cpu = pv.cpu_history.iter().copied().fold(0.0f32, f32::max);
        let cpu_top = ceiling_for(peak_cpu, &[5.0, 10.0, 25.0, 50.0, 100.0]);
        graph(ui, t, Rect::from_min_size(row.min, vec2(w, 120.0)), "Memory, last minute", &pv.memory_history, memory_top, &format!("{memory_top:.0} MB"), t.accent);
        graph(ui, t, Rect::from_min_size(pos2(row.left() + w + gap, row.top()), vec2(w, 120.0)), "Processor, last minute", &pv.cpu_history, cpu_top, &format!("{cpu_top:.0}%"), Color32::from_rgb(0x23, 0xa5, 0x5a));
        ui.add_space(20.0);

        // ---- the processes ----
        ui.label(RichText::new("Processes").font(strong(16.0)).color(t.header_primary));
        ui.add_space(8.0);
        // Columns: name (the rest), then right-aligned figures.
        let columns = [("PID", 70.0), ("Processor", 86.0), ("Memory", 92.0), ("Threads", 72.0)];
        let figures: f32 = columns.iter().map(|c| c.1).sum();
        let (head, _) = ui.allocate_exact_size(vec2(width, 28.0), Sense::hover());
        ui.painter().text(pos2(head.left() + 12.0, head.center().y), Align2::LEFT_CENTER, "Name", strong(12.0), t.text_muted);
        let mut x = head.right() - 12.0 - figures;
        for (label, w) in columns {
            x += w;
            ui.painter().text(pos2(x, head.center().y), Align2::RIGHT_CENTER, label, strong(12.0), t.text_muted);
        }
        ui.painter().hline(head.x_range(), head.bottom(), Stroke::new(1.0_f32, t.border_subtle));
        for (i, p) in pv.processes.iter().enumerate() {
            let (r, resp) = ui.allocate_exact_size(vec2(width, 40.0), Sense::hover());
            if resp.hovered() {
                ui.painter().rect_filled(r, 6.0, overlay(0.06));
            }
            // Helpers sit a step in under RustCord.
            let indent = if i == 0 { 0.0 } else { 18.0 };
            let name = describe(p, i == 0);
            let clip = ui.painter_at(Rect::from_min_max(r.min, pos2(r.right() - 12.0 - figures - 8.0, r.bottom())));
            clip.text(pos2(r.left() + 12.0 + indent, r.center().y), Align2::LEFT_CENTER, &name, medium(15.0), if i == 0 { t.header_primary } else { t.text_normal });
            let cells = [p.pid.to_string(), pv.cpu.get(&p.pid).map_or_else(|| "–".to_string(), |c| percent(*c)), mb(memory(p)), p.threads.to_string()];
            let mut x = r.right() - 12.0 - figures;
            for ((_, w), text) in columns.iter().zip(cells) {
                x += w;
                ui.painter().text(pos2(x, r.center().y), Align2::RIGHT_CENTER, text, FontId::proportional(14.0), t.text_normal);
            }
            resp.on_hover_text(format!("{}\nIn RAM with shared: {}\nReserved (commit): {}\nHandles: {}", p.name, mb(p.working_set), mb(p.committed), p.handles));
            ui.painter().hline(r.x_range(), r.bottom(), Stroke::new(1.0_f32, t.border_subtle));
        }
        if pv.processes.is_empty() {
            ui.add_space(8.0);
            ui.label(RichText::new("Process details aren't available on this system.").size(14.0).color(t.text_muted));
        }
        ui.add_space(20.0);

        // ---- RustCord itself, in more detail ----
        if let Some(me) = pv.processes.first() {
            ui.label(RichText::new("RustCord in detail").font(strong(16.0)).color(t.header_primary));
            ui.add_space(8.0);
            let up = ui.input(|i| i.time) as u64;
            let uptime = if up >= 3600 { format!("{} h {} min", up / 3600, up % 3600 / 60) } else if up >= 60 { format!("{} min {} s", up / 60, up % 60) } else { format!("{up} s") };
            let rows = [
                ("Reserved memory (commit)", mb(me.committed), format!("Memory {SYSTEM} has set aside for RustCord, whether it is in RAM or not.")),
                ("Most in RAM since it started", mb(me.peak_working_set), "The highest the \"In RAM, with shared\" figure has been.".to_string()),
                ("Processor time used", format!("{:.1} s", me.cpu_seconds), "Total processor time since RustCord started.".to_string()),
                ("Handles", me.handles.to_string(), "Open files, connections and other system objects.".to_string()),
                ("Running for", uptime, String::new()),
            ];
            for (label, value, hint) in rows {
                let (r, resp) = ui.allocate_exact_size(vec2(width, 32.0), Sense::hover());
                ui.painter().text(pos2(r.left() + 12.0, r.center().y), Align2::LEFT_CENTER, label, FontId::proportional(14.0), t.text_normal);
                ui.painter().text(pos2(r.right() - 12.0, r.center().y), Align2::RIGHT_CENTER, value, medium(14.0), t.header_primary);
                ui.painter().hline(r.x_range(), r.bottom(), Stroke::new(1.0_f32, t.border_subtle));
                if !hint.is_empty() {
                    resp.on_hover_text(hint);
                }
            }
            ui.add_space(20.0);
        }

        // ---- hand memory back ----
        let mut free = false;
        ui.horizontal(|ui| {
            ui.spacing_mut().button_padding = vec2(14.0, 4.0);
            let button =egui::Button::new(RichText::new("Free unused memory").font(medium(14.0)).color(t.header_primary)).fill(overlay(0.12)).rounding(8.0).min_size(vec2(0.0, 32.0));
            free = ui.add(button).on_hover_cursor(egui::CursorIcon::PointingHand).clicked();
            ui.add_space(8.0);
            if let Some((freed, _)) = pv.freed.filter(|(_, at)| at.elapsed() < Duration::from_secs(8)) {
                let text = if freed > 0 { format!("Handed {freed} MB back to {SYSTEM}.") } else { "Nothing more to hand back.".to_string() };
                ui.label(RichText::new(text).size(14.0).color(t.text_muted));
            }
        });
        ui.add_space(6.0);
        ui.add(egui::Label::new(RichText::new(format!("Hands memory RustCord isn't using back to {SYSTEM}. RustCord also does this by itself when it has been quiet for a while.")).size(13.0).color(t.text_muted)).wrap());
        if free {
            let before = crate::diagnostics::working_set_mb() as i64;
            crate::diagnostics::release_unused_memory();
            crate::diagnostics::trim_working_set();
            let after = crate::diagnostics::working_set_mb() as i64;
            self.process_viewer.freed = Some((before - after, Instant::now()));
            self.process_viewer.sample();
        }
    }
}