//! 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::disclosure; use crate::fmt; use crate::theme; 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()); theme::install(ctx); 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) { // The whole window in the page colour first: the toolbar sits outside the // scrolling panel, and the browser's own canvas colour must never show. ui.painter() .rect_filled(ui.max_rect(), 0.0, theme::ctx(ui.ctx()).page); controls(self, ui); if let (Some(view), Some(error)) = (&self.view, &self.error) { lost_contact( ui.ctx(), error, view.generated_at, ui.available_rect_before_wrap().width(), ); } egui::CentralPanel::default() .frame( egui::Frame::NONE .fill(theme::ctx(ui.ctx()).page) .inner_margin(egui::Margin::symmetric( theme::space::PAGE_MARGIN as i8, theme::space::PAGE_MARGIN as i8, )), ) .show(ui, |ui| { egui::ScrollArea::vertical() .auto_shrink([false; 2]) .show(ui, |ui| { let Self { range, view, hidden_languages, .. } = self; match view { None => waiting(ui, self.error.as_deref(), self.refresh_secs), Some(view) => page(ui, view, *range, 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)) } fn theme_labels() -> [&'static str; 3] { ThemeChoice::ALL.map(|theme| theme.name()) } /// The wordmark at the left of the top bar. fn wordmark(ui: &mut egui::Ui) { ui.add(egui::Label::new( egui::RichText::new("sccache dash") .font(theme::number_font(15.0)) .color(theme::ui(ui).text), )); } fn wordmark_width(ui: &egui::Ui) -> f32 { style::text_width(ui, "sccache dash", theme::number_font(15.0)) } /// About how wide the row of actions is, from the width of its labels. fn actions_width(ui: &egui::Ui) -> f32 { let medium = theme::medium(theme::px::BODY); let label = |text: &str| style::text_width(ui, text, medium.clone()) + 18.0; let gaps = theme::space::TOOL_GAP; label(&fmt::refresh_label(30)) + 20.0 + label("Refresh") + theme_labels().iter().map(|text| style::text_width(ui, text, medium.clone()) + 2.0 * theme::space::CONTROL_PAD).sum::() + label("Copy summary") + label("Export JSON") + label("Zero stats") + theme::space::TOOLBAR_NOTE_WIDTH + gaps * 7.0 } /// The slim bar at the top of the page: the wordmark and the range at the left; the /// actions at the right, on their own line where there is no room beside the range. fn controls(dashboard: &mut Dashboard, ui: &mut egui::Ui) { let ctx = ui.ctx().clone(); let now = Dashboard::now(&ctx); let gap = theme::space::TOOL_GAP; let margin = theme::space::PAGE_MARGIN; let vertical = 10.0; ui.add_space(vertical); let width = ui.available_rect_before_wrap().width() - 2.0 * margin; let medium = theme::medium(theme::px::BODY); let range_width: f32 = Range::ALL .iter() .map(|range| style::text_width(ui, range.code(), medium.clone()) + 2.0 * theme::space::CONTROL_PAD) .sum(); let left_width = wordmark_width(ui) + 2.0 * theme::space::PANEL_GAP + range_width; let one_line = left_width + gap + actions_width(ui) <= width; let phone = width + 2.0 * theme::space::PAGE_MARGIN < theme::layout::TWO_COLUMNS_FROM; let labels: Vec<&str> = Range::ALL.iter().map(|range| range.code()).collect(); let chosen = Range::ALL.iter().position(|range| *range == dashboard.range).unwrap_or(0); ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = gap; ui.add_space(margin); wordmark(ui); ui.add_space(theme::space::PANEL_GAP - gap); if let Some(index) = style::segmented(ui, "range", &labels, chosen) { if index != chosen { dashboard.range = Range::ALL[index]; dashboard.settings_changed = true; dashboard.send(&ctx, Ask::View); } } if one_line { ui.add_space((ui.available_width() - actions_width(ui) - margin).max(0.0)); ui.allocate_ui_with_layout( egui::vec2(actions_width(ui), theme::layout::TOOLBAR_HEIGHT), egui::Layout::left_to_right(egui::Align::Center), |ui| actions(dashboard, ui, &ctx, now, gap), ); } }); if !one_line { let height = theme::layout::TOOLBAR_HEIGHT; ui.add_space(gap); let room = ui.available_rect_before_wrap().width() - 2.0 * margin; let group_width = if phone { room } else { actions_width(ui).min(room) }; // On a phone the actions wrap at the left; on a narrower window they sit // on a second line, at the right. let layout = if phone { egui::Layout::left_to_right(egui::Align::Center).with_main_wrap(true) } else { egui::Layout::right_to_left(egui::Align::Center) }; ui.horizontal(|ui| { ui.add_space(margin); ui.allocate_ui_with_layout(egui::vec2(room, height), layout, |ui| { if !phone { ui.allocate_ui_with_layout( egui::vec2(group_width, height), egui::Layout::left_to_right(egui::Align::Center), |ui| actions(dashboard, ui, &ctx, now, gap), ); } else { ui.spacing_mut().item_spacing = egui::vec2(gap, gap); actions(dashboard, ui, &ctx, now, gap); } }); }); } ui.add_space(vertical); let rule = ui.available_rect_before_wrap(); ui.painter().hline( rule.x_range(), rule.top() + 0.5, egui::Stroke::new(1.0, theme::ctx(&ctx).border), ); ui.add_space(1.0); } /// Refresh, theme, Copy summary, Export JSON, Zero stats, and the message slot. fn actions(dashboard: &mut Dashboard, ui: &mut egui::Ui, ctx: &egui::Context, now: f64, gap: f32) { ui.spacing_mut().item_spacing.x = gap; 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); } let theme_chosen = ThemeChoice::ALL .iter() .position(|theme| *theme == dashboard.theme) .unwrap_or(0); if let Some(index) = style::segmented(ui, "theme", &theme_labels(), theme_chosen) { let theme = ThemeChoice::ALL[index]; dashboard.theme = theme; dashboard.settings_changed = true; ctx.set_theme(theme.preference()); } 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.allocate_ui_with_layout( egui::vec2(theme::space::TOOLBAR_NOTE_WIDTH, theme::layout::TOOLBAR_HEIGHT), egui::Layout::left_to_right(egui::Align::Center), |ui| { if dashboard .pending .as_ref() .is_some_and(|(ask, _)| *ask == Ask::View) { ui.spinner(); ui.add(egui::Label::new(theme::small(ui, "Updating")).truncate()); } else if let Some((note, _)) = &dashboard.note { ui.add(egui::Label::new(theme::small(ui, note.clone())).truncate()); } }, ); } /// 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.add(egui::Label::new(theme::strong("Zero sccache's stats?")).wrap()); ui.add_space(theme::space::ITEM); ui.add(egui::Label::new(theme::body( "The counters go back to zero. The saved history stays, so the charts keep their \ older data. This can't be undone.", )) .wrap()); ui.add_space(theme::space::PANEL_GAP); 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 p = theme::ui(ui); 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}" ), p.bad, ), None => ( "Waiting for the first figures".to_owned(), "Asking the server for your cache numbers.".to_owned(), p.text, ), }; // The same height the headline and cards take, so the page doesn't jump when they arrive. let width = ui.available_rect_before_wrap().width(); let height = theme::layout::HEADLINE_HEIGHT + theme::space::PANEL_GAP + theme::layout::STRIP_ROW_HEIGHT * 2.0; let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover()); let mut place = ui.new_child( egui::UiBuilder::new() .max_rect(rect) .layout(egui::Layout::centered_and_justified(egui::Direction::TopDown)), ); place.vertical(|ui| { ui.add(egui::Label::new(theme::strong(heading).color(color)).wrap()); ui.add(egui::Label::new(theme::small(ui, body)).wrap()); }); } /// A notice that the server can't be reached, shown over the page rather than /// in it, so what is already on screen keeps its place and height. fn lost_contact(ctx: &egui::Context, error: &str, from: i64, page_width: f32) { let p = theme::ctx(ctx); let when = fmt::moment_text(from + fmt::local_offset()); egui::Area::new(egui::Id::unique("lost-contact")) .anchor( egui::Align2::RIGHT_TOP, egui::vec2(-theme::space::PAGE_MARGIN, theme::layout::TOOLBAR_HEIGHT + 3.0 * theme::space::PAGE_MARGIN), ) .order(egui::Order::Foreground) .show(ctx, |ui| { let width = (page_width - 2.0 * theme::space::PAGE_MARGIN).min(440.0); egui::Frame::NONE .fill(p.panel) .stroke(egui::Stroke::new(1.0, p.bad)) .corner_radius(theme::space::PANEL_RADIUS) .inner_margin(theme::space::PANEL_PAD_Y) .show(ui, |ui| { ui.set_max_width(width - 2.0 * theme::space::PANEL_PAD_Y); ui.add( egui::Label::new( theme::strong(format!( "Can't reach the server: {error}. These figures are from {when}." )) .color(p.bad), ), ); }); }); } /// The rectangles of one row of the grid: each entry of `spans` is how many /// columns that panel takes; all are at least `height` tall. fn row(ui: &egui::Ui, height: f32, spans: &[usize]) -> Vec { style::cells(ui, height, spans) } /// Close the row: the cursor moves below the tallest of its panels. fn close_row(ui: &mut egui::Ui, taken: &[egui::Rect]) { style::end_row(ui, taken); } /// One panel across the whole page, as tall as what it holds. fn single(ui: &mut egui::Ui, title: &str, body: impl FnOnce(&mut egui::Ui)) { let [rect] = row(ui, 0.0, &[1]).try_into().expect("one panel"); let (_, taken) = style::panel(ui, rect, title, body); close_row(ui, &[taken]); } /// How tall a panel is that holds `rows` table rows under its title. fn table_height(fixed: f32, rows: usize) -> f32 { fixed + rows as f32 * theme::space::ROW } /// How tall "Speed" is. fn speed_height(view: &View) -> f32 { use theme::layout as l; let with_histograms = view .build_times .iter() .filter(|times| times.compiles > 0 && !times.bins.is_empty()) .count(); table_height(l::SPEED_FIXED_HEIGHT, 0) + with_histograms as f32 * l::HISTOGRAM_HEIGHT } /// The whole page below the controls: a grid of panels. Two columns of panels /// from the medium width up, one below it; the counter strip is six across, /// three across, or two. fn page(ui: &mut egui::Ui, view: &View, asked: Range, hidden_languages: &mut Vec) { let p = theme::ui(ui); use theme::layout as l; let gap = theme::space::PANEL_GAP; if let Some(error) = &view.server.error { style::banner(ui, egui::RichText::new(format!("sccache is not working: {error}")), p.bad); ui.add_space(gap); } let columns = theme::columns(ui.available_rect_before_wrap().width()); headline(ui, view, asked); // Six counters in one row on a wide screen; three in the medium layout; two on a phone. let per_row = match columns { 3 => 6, 2 => 3, _ => 2, }; cards::row(ui, view, per_row); if columns >= 2 { let half = style::span_width(ui, 2, 1); let languages_h = table_height(l::LANGUAGES_FIXED_HEIGHT, view.languages.len() + 1); let [a, b] = row(ui, l::WHERE_FIXED_HEIGHT.max(languages_h), &[1, 1]).try_into().expect("two panels"); let (_, a) = style::panel(ui, a, "Where compiles went", |ui| where_went::section(ui, view)); let (_, b) = style::panel(ui, b, "By language", |ui| where_went::languages(ui, view)); close_row(ui, &[a, b]); overtime::filter(ui, view, hidden_languages); ui.add_space(theme::space::ITEM); let hidden: &[String] = hidden_languages; let [a, b] = row(ui, l::CHART_PANEL_HEIGHT, &[1, 1]).try_into().expect("two panels"); let (_, a) = style::panel(ui, a, "Hit rate over time", |ui| { overtime::hit_rate_panel(ui, view, hidden, theme::drawing::CHART_HEIGHT) }); let (_, b) = style::panel(ui, b, "Compiles over time", |ui| { overtime::volume_panel(ui, view, hidden, theme::drawing::CHART_HEIGHT) }); close_row(ui, &[a, b]); let height = speed_height(view).max(where_went::reasons_height(ui, view, half)); let [a, b] = row(ui, height, &[1, 1]).try_into().expect("two panels"); let (_, a) = style::panel(ui, a, "Speed", |ui| speed::section(ui, view)); let (_, b) = style::panel(ui, b, "Why compiles were not cacheable", |ui| where_went::reasons(ui, view)); close_row(ui, &[a, b]); } else { // One column: each panel as tall as what it holds. single(ui, "Where compiles went", |ui| where_went::section(ui, view)); single(ui, "By language", |ui| where_went::languages(ui, view)); overtime::filter(ui, view, hidden_languages); ui.add_space(theme::space::ITEM); let hidden: &[String] = hidden_languages; single(ui, "Hit rate over time", |ui| { overtime::hit_rate_panel(ui, view, hidden, theme::drawing::CHART_HEIGHT) }); single(ui, "Compiles over time", |ui| { overtime::volume_panel(ui, view, hidden, theme::drawing::CHART_HEIGHT) }); single(ui, "Speed", |ui| speed::section(ui, view)); single(ui, "Why compiles were not cacheable", |ui| where_went::reasons(ui, view)); } extras(ui, view); let open = ui .ctx() .data_mut(|data| data.get_temp::(egui::Id::new("raw-counters-open"))) .unwrap_or(false); let full = style::span_width(ui, 1, 1); let [rect] = row(ui, raw::height(view, full, open), &[1]).try_into().expect("one panel"); let taken = raw::section(ui, view, rect); close_row(ui, &[taken]); ui.add_space(theme::space::PAGE_MARGIN); } /// The "Extras" panels, side by side where there are several. fn extras(ui: &mut egui::Ui, view: &View) { if view.extras.is_empty() { return; } let columns = theme::columns(ui.available_rect_before_wrap().width()).min(2); let per_row = columns.min(view.extras.len()).max(1); for line in view.extras.chunks(per_row) { let spans: Vec = line.iter().map(|_| 1).collect(); let height = theme::space::ROW * (line.iter().map(|extra| extra.rows.len()).max().unwrap_or(0) + 1) as f32 + theme::space::PANEL_PAD_Y * 2.0 + theme::space::UNDER_TITLE + 12.0; let cells = style::cells(ui, height, &spans); let mut taken = Vec::with_capacity(cells.len()); for (rect, extra) in cells.iter().zip(line) { let title: &str = Box::leak(extra.title.clone().into_boxed_str()); let (_, rect) = style::panel(ui, *rect, title, |ui| extras::section(ui, view)); taken.push(rect); } close_row(ui, &taken); } } /// One of the three big figures. struct Figure<'a> { value: String, /// The size of the figure's text: a number, or words at the card size. size: f32, color: egui::Color32, caption: String, /// Smaller print under the figure. small: String, /// A second line of smaller print; the block keeps its height when it is empty. small2: String, /// A trend line and the value it is drawn against. trend: Option<(&'a [Option], f64)>, /// Instead of a trend line and small print: the problems list. problems: Option<&'a View>, hover: Option, } /// The line the figure's number sits on: every figure's number has this much room, so all /// the captions below start at the same height whatever size the number is drawn at. const VALUE_ROW: f32 = theme::px::HEADLINE * 1.25; /// The room the storage line (meter and text) is given under the figures; a phone has a second text line. const STORAGE_LINE: f32 = 30.0; impl Figure<'_> { /// Draw in a column `width` wide and always the same height. fn draw(self, ui: &mut egui::Ui, width: f32) { let gap = theme::space::LINE; let block = ui.allocate_ui_with_layout( egui::vec2(width, theme::layout::FIGURE_HEIGHT), egui::Layout::top_down(egui::Align::Min), |ui| { ui.set_width(width); ui.spacing_mut().item_spacing = egui::vec2(gap, gap); // Shrink a long figure to the column instead of cutting it. let natural = style::text_width(ui, &self.value, theme::number_font(self.size)); let size = if natural > width { (self.size * width / natural).max(20.0) } else { self.size }; ui.allocate_ui_with_layout( egui::vec2(width, VALUE_ROW), egui::Layout::left_to_right(egui::Align::Max), |ui| { let value = egui::Label::new( egui::RichText::new(&self.value) .font(theme::number_font(size)) .color(self.color), ) .truncate(); ui.add(value.sense(egui::Sense::hover())).on_hover_text(&self.value); }, ); ui.add(egui::Label::new(theme::title(ui, self.caption.clone())).truncate()); ui.add_space(gap * 2.0); if let Some(view) = self.problems { let room = ui.available_height(); problems::hero_list(ui, view, room); return; } match self.trend { Some((values, top)) => style::sparkline(ui, theme::drawing::SPARKLINE, values, top, self.color), None => ui.add_space(theme::drawing::SPARKLINE + gap), } ui.add(egui::Label::new(theme::small(ui, self.small.clone())).truncate()); ui.add(egui::Label::new(theme::small(ui, self.small2.clone())).truncate()); }, ); if let Some(hover) = self.hover { block.response.on_hover_text(hover); } } } /// The big numbers, what they mean, and where the cache lives. fn headline(ui: &mut egui::Ui, view: &View, asked: Range) { let range = view.range.unwrap_or(asked); let totals = &view.totals; let p = theme::ui(ui); 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 counts = format!( "{} compiles · {} from cache · {} built", fmt::count(totals.requests), fmt::count(totals.hits), fmt::count(totals.misses) ); let title_text = theme::title(ui, range.label()).text().to_owned(); let counts_text = counts.clone(); let width = ui.available_rect_before_wrap().width(); // Side by side where there is room; one under another on a phone. let side_by_side = width >= 600.0; let spacing = theme::space::PANEL_GAP; let height = if side_by_side { theme::layout::HEADLINE_HEIGHT } else { theme::layout::HEADLINE_HEIGHT + 2.0 * (theme::layout::FIGURE_HEIGHT + spacing) + STORAGE_LINE / 2.0 }; let rect = egui::Rect::from_min_size(ui.cursor().min, egui::vec2(width, height)); let (_, taken) = style::panel_titled( ui, rect, |ui| { ui.horizontal(|ui| { ui.add(egui::Label::new(theme::title(ui, title_text)).truncate()); ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.add(egui::Label::new(theme::small(ui, counts_text)).truncate()); }); }); }, |ui| { let width = ui.available_rect_before_wrap().width(); let columns = if side_by_side { 3.0 } else { 1.0 }; let column = (width - spacing * (columns - 1.0)) / columns; ui.add_space(theme::space::ITEM); let draw = |ui: &mut egui::Ui, figure: Figure<'_>| figure.draw(ui, column); // Timeouts, cache errors and forced recaches are inside the built count, as sccache counts them. let first = Figure { value: fmt::percent(totals.hit_rate()), size: theme::px::HEADLINE, color: p.hero, caption: "from cache".into(), small: format!("{} of all compiler calls", fmt::percent(totals.hit_rate_of_all())), trend: Some((&rates, 1.0)), problems: None, hover: None, small2: String::new(), }; // A saving is never written in milliseconds; and when no language's build time is // known yet, the figure says so instead of showing nothing. let seconds = view.time_saved.seconds; let left_out = view.time_saved.hits_left_out; let left_out_line = if left_out > 0 { format!("{} hits left out of this figure", fmt::count(left_out)) } else { "every hit counted".to_owned() }; let interval = view .time_saved .interval_90 .map(|(low, high)| format!("{} – {} (90% range)", fmt::duration(low), fmt::duration(high))); let (value, size, small, small2) = if seconds >= 1.0 { (format!("~{}", fmt::duration(seconds)), theme::px::HEADLINE, interval.unwrap_or_default(), left_out_line) } else if seconds > 0.0 { ("~under 1 s".to_owned(), theme::px::HEADLINE, interval.unwrap_or_default(), left_out_line) } else if left_out > 0 { ( "not enough data yet".to_owned(), theme::px::CARD_NUMBER, String::new(), format!( "{} hits not counted: no build time known yet for their language", fmt::count(left_out) ), ) } else { ("nothing saved yet".to_owned(), theme::px::CARD_NUMBER, String::new(), String::new()) }; let second = Figure { value, size, color: p.hero, caption: "saved (rough)".into(), small, small2, trend: Some((&saved, saved_top)), problems: None, hover: Some(view.time_saved.note.clone()), }; let third = Figure { value: fmt::count(problems as u64), size: theme::px::HEADLINE, color: if problems > 0 { p.bad } else { p.text }, caption: if problems == 1 { "problem".into() } else { "problems".into() }, small: String::new(), small2: String::new(), trend: None, problems: Some(view), hover: None, }; let top = ui.cursor().top(); let left = ui.cursor().left(); if side_by_side { ui.horizontal_top(|ui| { ui.spacing_mut().item_spacing.x = spacing; draw(ui, first); draw(ui, second); draw(ui, third); }); // A hairline in the middle of each gutter between figures. let y = top..=top + theme::layout::FIGURE_HEIGHT; for index in 1..3 { let x = left + index as f32 * column + (index as f32 - 0.5) * spacing; ui.painter().vline(x.round() + 0.5, y.clone(), egui::Stroke::new(1.0, p.grid)); } } else { draw(ui, first); ui.add_space(spacing); draw(ui, second); ui.add_space(spacing); draw(ui, third); } ui.add_space(theme::space::ITEM); style::rule(ui); ui.add_space(theme::space::ITEM + 2.0); 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 = parts.join(" · "); // The meter first, then the text under it, in a box of fixed height. let lines = if side_by_side { 1.0 } else { 2.0 }; let text_height = STORAGE_LINE / 2.0 * lines; 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 >= theme::state::CACHE_FULL { p.bad } else { p.hero }; style::meter(ui, theme::drawing::USAGE_BAR, full, color); ui.add_space(theme::space::ITEM); } let response = ui .allocate_ui_with_layout( egui::vec2(width, text_height), egui::Layout::top_down(egui::Align::Min), |ui| ui.add(egui::Label::new(theme::small(ui, line)).wrap()), ) .inner; if let Some(location) = &server.cache_location { response.on_hover_text(location.clone()); } }, ); ui.allocate_rect(taken, egui::Sense::hover()); ui.add_space(theme::space::PANEL_GAP); }