//! The dashboard: what it remembers, how it fetches, and the top of the page. use std::time::Duration; use eframe::egui; use sccache_dash_api::{Range, View}; use crate::fmt; use crate::{cards, extras, net, overtime, problems, raw, speed, style, where_went}; /// Refresh intervals offered, in seconds; zero means off. const REFRESH_CHOICES: [u64; 4] = [0, 5, 10, 30]; #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] enum ThemeChoice { /// Follow the browser's own light or dark setting. Auto, Light, Dark, } impl ThemeChoice { const ALL: [Self; 3] = [Self::Auto, Self::Light, Self::Dark]; fn name(self) -> &'static str { match self { Self::Auto => "Auto", Self::Light => "Light", Self::Dark => "Dark", } } fn preference(self) -> egui::ThemePreference { match self { Self::Auto => egui::ThemePreference::System, Self::Light => egui::ThemePreference::Light, Self::Dark => egui::ThemePreference::Dark, } } } /// What a request in flight is for. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Ask { View, Zero, } /// The whole page. It draws one `View` at a time and keeps the last one on /// screen until the next arrives. pub struct Dashboard { range: Range, refresh_secs: u64, theme: ThemeChoice, view: Option, pending: Option<(Ask, net::Answer)>, /// Why the last request failed, if it did. error: Option, /// Page time, in seconds, when the last view was asked for. sent_at: Option, /// Languages unticked in the "Over time" filter. hidden_languages: Vec, /// Whether the "Zero stats" question is open. asking_zero: bool, /// A short message for the controls row, and the page time it goes away. note: Option<(String, f64)>, /// Set when the range, refresh interval or theme changed and should be remembered. settings_changed: bool, } impl Dashboard { pub fn new(cc: &eframe::CreationContext<'_>) -> Self { let storage = cc.storage; let dashboard = Self { range: remembered(storage, "range").unwrap_or(Range::Day), refresh_secs: remembered(storage, "refresh").unwrap_or(10), theme: remembered(storage, "theme").unwrap_or(ThemeChoice::Auto), view: None, pending: None, error: None, sent_at: None, hidden_languages: Vec::new(), asking_zero: false, note: None, settings_changed: false, }; let ctx = &cc.egui_ctx; ctx.set_theme(dashboard.theme.preference()); ctx.all_styles_mut(|style| { style .text_styles .insert(egui::TextStyle::Small, egui::FontId::proportional(11.5)); style.spacing.item_spacing = egui::vec2(8.0, 4.0); }); dashboard } fn now(ctx: &egui::Context) -> f64 { ctx.input(|input| input.time) } /// Send a request, replacing any request still in flight. fn send(&mut self, ctx: &egui::Context, ask: Ask) { if ask == Ask::View { self.sent_at = Some(Self::now(ctx)); } let request = match ask { Ask::View => net::view(self.range), Ask::Zero => net::zero(), }; self.pending = Some((ask, net::Answer::send(request, ctx))); } /// Pick up the answer to the request in flight, if it has arrived. fn collect(&mut self, ctx: &egui::Context, now: f64) { if self.note.as_ref().is_some_and(|(_, until)| *until <= now) { self.note = None; } let Some(answer) = self .pending .as_ref() .and_then(|(_, answer)| answer.take()) else { return; }; let Some((ask, _)) = self.pending.take() else { return; }; match ask { Ask::View => match net::view_from(answer) { Ok(view) => { self.view = Some(view); self.error = None; } Err(error) => self.error = Some(error), }, Ask::Zero => match net::accepted(answer) { Ok(()) => { self.flash("Stats zeroed", now); self.send(ctx, Ask::View); } Err(error) => self.error = Some(format!("The stats could not be zeroed: {error}")), }, } } /// Keep asking for a new view at the chosen interval. fn tick(&mut self, ctx: &egui::Context, now: f64) { if self.pending.is_some() { return; } let Some(sent_at) = self.sent_at else { self.send(ctx, Ask::View); return; }; if self.refresh_secs == 0 { return; } let every = self.refresh_secs as f64; let since = now - sent_at; if since >= every { self.send(ctx, Ask::View); } else { ctx.request_repaint_after(Duration::from_secs_f64((every - since).max(0.05))); } } fn flash(&mut self, text: impl Into, now: f64) { self.note = Some((text.into(), now + 4.0)); } } impl eframe::App for Dashboard { /// Runs before every frame, also while the window is hidden: pick up answers and keep asking. fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) { let now = Self::now(ctx); self.collect(ctx, now); self.tick(ctx, now); } fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { controls(self, ui); egui::CentralPanel::default().show(ui, |ui| { egui::ScrollArea::vertical() .auto_shrink([false; 2]) .show(ui, |ui| { ui.add_space(8.0); let Self { range, view, error, hidden_languages, .. } = self; match view { None => waiting(ui, error.as_deref(), self.refresh_secs), Some(view) => { page(ui, view, *range, error.as_deref(), hidden_languages) } } }); }); if self.asking_zero { zero_question(self, ui.ctx()); } if self.settings_changed { if let Some(storage) = frame.storage_mut() { remember(self, storage); } self.settings_changed = false; } } /// Remember the range, refresh interval and theme when the page is closed. fn save(&mut self, storage: &mut dyn eframe::Storage) { remember(self, storage); } } /// Put the range, refresh interval and theme into the storage eframe keeps between visits. fn remember(dashboard: &Dashboard, storage: &mut dyn eframe::Storage) { eframe::set_value(storage, "range", &dashboard.range); eframe::set_value(storage, "refresh", &dashboard.refresh_secs); eframe::set_value(storage, "theme", &dashboard.theme); } fn remembered( storage: Option<&dyn eframe::Storage>, key: &str, ) -> Option { storage.and_then(|storage| eframe::get_value(storage, key)) } /// The row of controls that stays at the top of the page. fn controls(dashboard: &mut Dashboard, ui: &mut egui::Ui) { let ctx = ui.ctx().clone(); let now = Dashboard::now(&ctx); egui::Panel::top("controls").show(ui, |ui| { ui.add_space(6.0); ui.horizontal_wrapped(|ui| { for range in Range::ALL { if ui .add(egui::Button::selectable( dashboard.range == range, range.code(), )) .clicked() { dashboard.range = range; dashboard.settings_changed = true; dashboard.send(&ctx, Ask::View); } } ui.add_space(8.0); let mut refresh_secs = dashboard.refresh_secs; egui::ComboBox::from_id_salt("refresh") .selected_text(fmt::refresh_label(refresh_secs)) .show_ui(ui, |ui| { for secs in REFRESH_CHOICES { ui.selectable_value(&mut refresh_secs, secs, fmt::refresh_label(secs)); } }); if refresh_secs != dashboard.refresh_secs { dashboard.refresh_secs = refresh_secs; dashboard.settings_changed = true; } if ui.button("Refresh").clicked() { dashboard.send(&ctx, Ask::View); } ui.add_space(8.0); for theme in ThemeChoice::ALL { if ui .add(egui::Button::selectable(dashboard.theme == theme, theme.name())) .clicked() { dashboard.theme = theme; dashboard.settings_changed = true; ctx.set_theme(theme.preference()); } } ui.add_space(8.0); let online = dashboard.view.is_some(); let copy = ui.add_enabled(online, egui::Button::new("Copy summary")); if copy.clicked() { if let Some(view) = &dashboard.view { ctx.copy_text(view.summary_markdown.clone()); } dashboard.flash("Summary copied", now); } let export = ui.add_enabled(online, egui::Button::new("Export JSON")); if export.clicked() { let note = net::download("/api/export").map_or_else( |error| format!("Export failed: {error}"), |()| "Export started".to_owned(), ); dashboard.flash(note, now); } let zeroing = dashboard .pending .as_ref() .is_some_and(|(ask, _)| *ask == Ask::Zero); let zero = ui.add_enabled(online && !zeroing, egui::Button::new("Zero stats")); if zero.clicked() { dashboard.asking_zero = true; } // A fixed-size slot, so that messages come and go without moving the controls. ui.add_space(8.0); ui.allocate_ui_with_layout( egui::vec2(120.0, 20.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { if dashboard .pending .as_ref() .is_some_and(|(ask, _)| *ask == Ask::View) { ui.spinner(); ui.label(egui::RichText::new("Updating").small()); } else if let Some((note, _)) = &dashboard.note { ui.add(egui::Label::new(egui::RichText::new(note).small()).truncate()); } }, ); }); ui.add_space(6.0); }); } /// Ask before zeroing: it can't be undone. fn zero_question(dashboard: &mut Dashboard, ctx: &egui::Context) { let modal = egui::Modal::new(egui::Id::unique("zero-stats-question")).show(ctx, |ui| { ui.set_max_width(360.0); ui.label(egui::RichText::new("Zero sccache's stats?").strong()); ui.add(egui::Label::new( "The counters go back to zero. The saved history stays, so the charts keep their \ older data. This can't be undone.", ).wrap()); ui.horizontal(|ui| { if ui.button("Zero stats").clicked() { Some(true) } else if ui.button("Cancel").clicked() { Some(false) } else { None } }) .inner }); let answer = modal.inner; if modal.should_close() || answer == Some(false) { dashboard.asking_zero = false; } if answer == Some(true) { dashboard.asking_zero = false; dashboard.send(ctx, Ask::Zero); } } /// What the page says while no view has arrived yet. fn waiting(ui: &mut egui::Ui, error: Option<&str>, refresh_secs: u64) { let [_, _, bad] = style::marks(ui.visuals().dark_mode); let retry = if refresh_secs > 0 { format!("Trying again every {refresh_secs} seconds.") } else { "Press Refresh to try again.".to_owned() }; let (heading, body, color) = match error { Some(error) => ( "Can't reach the server".to_owned(), format!( "{error}.\n\nCheck that sccache-dash is running on this machine. {retry}" ), bad, ), None => ( "Waiting for the first figures".to_owned(), "Asking the server for your cache numbers.".to_owned(), ui.visuals().text_color(), ), }; // The same height the headline and cards take, so the page doesn't jump when they arrive. ui.allocate_ui_with_layout( egui::vec2(ui.available_rect_before_wrap().width(), 250.0), egui::Layout::centered_and_justified(egui::Direction::TopDown), |ui| { ui.vertical(|ui| { ui.label(egui::RichText::new(heading).size(20.0).color(color)); ui.add(egui::Label::new(body).wrap()); }); }, ); } /// The whole page below the controls. fn page( ui: &mut egui::Ui, view: &View, asked: Range, error: Option<&str>, hidden_languages: &mut Vec, ) { let dark = ui.visuals().dark_mode; let [_, _, bad] = style::marks(dark); if let Some(error) = error { let from = fmt::moment_text(view.generated_at + fmt::local_offset()); style::banner( ui, format!("Lost contact with the server: {error}. These figures are from {from}."), bad, ); } if let Some(error) = &view.server.error { style::banner(ui, format!("sccache is not working: {error}"), bad); } headline(ui, view, asked, dark); ui.add_space(10.0); cards::row(ui, view, dark); problems::section(ui, view, dark); where_went::section(ui, view, dark); overtime::section(ui, view, hidden_languages, dark); speed::section(ui, view); extras::section(ui, view); raw::section(ui, view); ui.add_space(12.0); } /// One of the three big figures. struct Figure<'a> { value: String, color: egui::Color32, caption: String, /// Smaller print under the figure. small: String, /// A second line of smaller print, kept so the block's height never changes. small2: String, /// A trend line and the value it is drawn against. trend: Option<(&'a [Option], f64)>, hover: Option, } impl Figure<'_> { /// Draw in a column `width` wide and always the same height. fn draw(self, ui: &mut egui::Ui, width: f32) { let gap = ui.spacing().item_spacing.y; let block = ui.allocate_ui_with_layout( egui::vec2(width, FIGURE_HEIGHT), egui::Layout::top_down(egui::Align::Min), |ui| { ui.set_width(width); ui.add( egui::Label::new(egui::RichText::new(&self.value).size(30.0).color(self.color)) .truncate(), ); ui.add(egui::Label::new(egui::RichText::new(&self.caption).small()).truncate()); match self.trend { Some((values, top)) => style::sparkline(ui, TREND_HEIGHT, values, top, self.color), None => ui.add_space(TREND_HEIGHT + gap), } ui.add(egui::Label::new(egui::RichText::new(&self.small).small().weak()).truncate()); ui.add(egui::Label::new(egui::RichText::new(&self.small2).small().weak()).truncate()); }, ); if let Some(hover) = self.hover { block.response.on_hover_text(hover); } } } const TREND_HEIGHT: f32 = 22.0; const FIGURE_HEIGHT: f32 = 120.0; /// The big numbers, what they mean, and where the cache lives. fn headline(ui: &mut egui::Ui, view: &View, asked: Range, dark: bool) { let range = view.range.unwrap_or(asked); let totals = &view.totals; let text_color = ui.visuals().text_color(); let rates: Vec> = view .buckets .iter() .map(|bucket| (!bucket.gap).then(|| overtime::hit_rate(bucket.hits, bucket.misses)).flatten()) .collect(); let saved: Vec> = view .buckets .iter() .map(|bucket| (!bucket.gap).then_some(bucket.saved_seconds)) .collect(); let saved_top = saved.iter().flatten().fold(0.0_f64, |top, seconds| top.max(*seconds)); let problems = view.problems.len(); let worst = view.problems.first(); let problem_color = match worst.map(|problem| problem.severity) { Some(sccache_dash_api::Severity::Error) => style::marks(dark)[2], Some(sccache_dash_api::Severity::Warning) => style::marks(dark)[1], None => text_color, }; ui.label(egui::RichText::new(range.label().to_uppercase()).strong()); let width = ui.available_rect_before_wrap().width(); let spacing = ui.spacing().item_spacing.x; // Side by side where there is room; one under another on a phone. let columns = if width >= 600.0 { 3.0 } else { 1.0 }; let column = (width - spacing * (columns - 1.0)) / columns; ui.horizontal_wrapped(|ui| { Figure { value: fmt::percent(totals.hit_rate()), color: style::hit_rate_color(totals.hit_rate(), dark), caption: "from cache".into(), small: format!("{} of all compiler calls", fmt::percent(totals.hit_rate_of_all())), trend: Some((&rates, 1.0)), hover: None, small2: String::new(), } .draw(ui, column); let left_out = view.time_saved.hits_left_out; // The 90% range goes first; the hits left out are the line under it. let interval = view .time_saved .interval_90 .map(|(low, high)| format!("{} – {} (90% range)", fmt::duration(low), fmt::duration(high))); Figure { value: format!("~{}", fmt::duration(view.time_saved.seconds)), color: text_color, caption: "saved (rough)".into(), small: interval.unwrap_or_default(), small2: if left_out > 0 { format!("{} hits left out of this figure", fmt::count(left_out)) } else { "every hit counted".into() }, trend: Some((&saved, saved_top)), hover: Some(view.time_saved.note.clone()), } .draw(ui, column); Figure { value: if problems == 1 { "1 problem".into() } else if problems == 0 { "No problems".into() } else { format!("{} problems", fmt::count(problems as u64)) }, color: problem_color, caption: worst .map(|problem| problem.title.clone()) .unwrap_or_else(|| "Nothing needs attention".into()), small: String::new(), small2: String::new(), trend: None, hover: None, } .draw(ui, column); }); // Timeouts, cache errors and forced recaches are inside the built count, as sccache counts them. let built = totals.misses; ui.add(egui::Label::new(format!( "{} compiles · {} from cache · {} built", fmt::count(totals.requests), fmt::count(totals.hits), fmt::count(built) )).wrap()); let server = &view.server; let mut parts = Vec::new(); if let Some(location) = &server.cache_location { // sccache words it `Local disk: "/home/me/.cache/sccache"`; the kind is enough here. let kind = location.split(':').next().unwrap_or(location); let kind = if kind.eq_ignore_ascii_case("LOCAL DISK") { "local disk".to_owned() } else { kind.to_owned() }; parts.push(kind); } if let (Some(size), Some(max)) = (server.cache_size, server.max_cache_size) { parts.push(format!("{} of {}", fmt::bytes(size), fmt::bytes(max))); } if let Some(version) = server.version.as_deref().or(server.client_version.as_deref()) { parts.push(format!("sccache {version}")); } parts.push( match server.status { sccache_dash_api::Status::Running => "running", sccache_dash_api::Status::Idle => "idle", sccache_dash_api::Status::NotRunning => "not running", } .to_owned(), ); let line = format!("Cache: {}", parts.join(" · ")); let response = ui.add(egui::Label::new(line).wrap()); if let Some(location) = &server.cache_location { response.on_hover_text(location.clone()); } if let (Some(size), Some(max)) = (server.cache_size, server.max_cache_size) { let full = if max > 0 { size as f64 / max as f64 } else { 0.0 }; let color = if full >= 0.95 { style::marks(dark)[2] } else { style::CACHE }; style::meter(ui, 6.0, full, color); } }