Files
sccache-dash/crates/ui/src/app.rs
T
swaits 7e864ad749 Fix round: readable selected segments, panels that fit, smaller fonts
- A selected segment is the accent with white text, in both themes.
- At three columns the row of "Where compiles went", "By language" and
  "Problems" is one modest height; the reasons table is its own panel,
  "Why compiles were not cacheable", stacked under "Speed" beside
  "Over time" and as tall together as it is. In the two-column and
  one-column layouts it follows "Where compiles went".
- Raw counters use every column; each value follows its key by 16 px,
  and a key ends in "..." only where the two do not fit.
- No blank row between a table's head and its first row.
- The five embedded fonts are subset to Latin text and the symbols the
  page uses with pyftsubset (hinting dropped); the wasm goes from
  5.49 MB to 4.11 MB.
2026-11-28 13:40:27 -07:00

923 lines
36 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 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::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<View>,
pending: Option<(Ask, net::Answer)>,
/// Why the last request failed, if it did.
error: Option<String>,
/// Page time, in seconds, when the last view was asked for.
sent_at: Option<f64>,
/// Languages unticked in the "Over time" filter.
hidden_languages: Vec<String>,
/// 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<String>, 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<T: serde::de::DeserializeOwned>(
storage: Option<&dyn eframe::Storage>,
key: &str,
) -> Option<T> {
storage.and_then(|storage| eframe::get_value(storage, key))
}
fn theme_labels() -> [&'static str; 3] {
ThemeChoice::ALL.map(|theme| theme.name())
}
/// 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()) + 22.0;
let gaps = theme::space::PANEL_GAP;
label(&fmt::refresh_label(30)) + label("Refresh")
+ theme_labels().iter().map(|text| style::text_width(ui, text, medium.clone()) + 2.0 * theme::space::CONTROL_PAD).sum::<f32>()
+ label("Copy summary") + label("Export JSON") + label("Zero stats")
+ theme::space::TOOLBAR_NOTE_WIDTH
+ gaps * 7.0
}
/// The row of controls that stays at the top of the page: the range as one
/// segmented control at the left; the actions at the right, on their own lines
/// 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::PANEL_GAP;
let margin = theme::space::PAGE_MARGIN;
ui.add_space(margin);
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 beside = width >= theme::layout::TOOLBAR_TWO_LINES_BELOW;
let one_line = beside && range_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);
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)).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(margin);
let room = ui.available_rect_before_wrap().width();
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.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(gap - theme::space::LINE);
}
/// 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::CARD_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 + 2.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_PADDING)
.show(ui, |ui| {
ui.set_max_width(width - 2.0 * theme::space::PANEL_PADDING);
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<egui::Rect> {
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 the row of "Where compiles went", "By language" and "Problems" is:
/// enough for the tallest of the three, and never less than the usual height.
fn triptych_height(view: &View) -> f32 {
use theme::layout as l;
l::TRIPTYCH_HEIGHT
.max(l::WHERE_FIXED_HEIGHT)
.max(table_height(l::LANGUAGES_FIXED_HEIGHT, view.languages.len()))
.max(problems_height(view))
}
/// 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
}
fn problems_height(view: &View) -> f32 {
use theme::layout as l;
if view.problems.is_empty() {
88.0
} else {
table_height(l::PROBLEMS_FIXED_HEIGHT, 0) + view.problems.len() as f32 * l::PROBLEM_HEIGHT
}
}
/// How tall the row of "Over time" is when "Speed" and "Why compiles were not
/// cacheable" are stacked beside it: the taller of the two sides.
fn charts_height(view: &View) -> f32 {
use theme::layout as l;
let stacked = speed_height(view)
+ theme::space::PANEL_GAP
+ where_went::reasons_height(view.not_cached.len());
l::CHARTS_HEIGHT.max(stacked)
}
/// How tall each chart of "Over time" is in a row `height` tall: the usual
/// height, plus the room a taller row leaves.
fn chart_height(height: f32) -> f32 {
let extra = (height - theme::layout::CHARTS_HEIGHT).max(0.0);
theme::drawing::CHART_HEIGHT + (extra / 2.0 - 2.0 * theme::space::LINE).max(0.0)
}
/// The whole page below the controls: a grid of panels.
fn page(ui: &mut egui::Ui, view: &View, asked: Range, hidden_languages: &mut Vec<String>) {
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 cards in one row on a wide screen; three in the two-column layout; two on a phone.
let per_row = match columns {
3 => 6,
2 => 3,
_ => 2,
};
cards::row(ui, view, per_row);
match columns {
3 => {
let [a, b, c] = row(ui, triptych_height(view), &[1, 1, 1]).try_into().expect("three 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));
let (_, c) = style::panel(ui, c, "Problems", |ui| problems::section(ui, view));
close_row(ui, &[a, b, c]);
// "Over time" over two columns; "Speed" and the reasons stacked in the third, together as tall.
let height = charts_height(view);
let [wide, side] = row(ui, height, &[2, 1]).try_into().expect("two panels");
let speed = speed_height(view);
let speed_rect = egui::Rect::from_min_max(side.min, egui::pos2(side.right(), side.top() + speed));
let reasons_rect = egui::Rect::from_min_max(egui::pos2(side.left(), side.top() + speed + gap), side.max);
let (_, wide) = style::panel(ui, wide, "Over time", |ui| {
overtime::section(ui, view, hidden_languages, chart_height(height))
});
let (_, speed) = style::panel(ui, speed_rect, "Speed", |ui| speed::section(ui, view));
let (_, reasons) = style::panel(ui, reasons_rect, "Why compiles were not cacheable", |ui| {
where_went::reasons(ui, view)
});
close_row(ui, &[wide, speed, reasons]);
}
2 => {
let reasons = where_went::reasons_height(view.not_cached.len());
let height = l::TRIPTYCH_HEIGHT.max(l::WHERE_FIXED_HEIGHT).max(reasons);
let [a, b] = row(ui, height, &[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, "Why compiles were not cacheable", |ui| where_went::reasons(ui, view));
close_row(ui, &[a, b]);
let height = l::TRIPTYCH_HEIGHT
.max(table_height(l::LANGUAGES_FIXED_HEIGHT, view.languages.len()))
.max(problems_height(view));
let [a, b] = row(ui, height, &[1, 1]).try_into().expect("two panels");
let (_, a) = style::panel(ui, a, "By language", |ui| where_went::languages(ui, view));
let (_, b) = style::panel(ui, b, "Problems", |ui| problems::section(ui, view));
close_row(ui, &[a, b]);
let [a] = row(ui, l::CHARTS_HEIGHT, &[2]).try_into().expect("one panel");
let (_, a) = style::panel(ui, a, "Over time", |ui| {
overtime::section(ui, view, hidden_languages, theme::drawing::CHART_HEIGHT)
});
close_row(ui, &[a]);
single(ui, "Speed", |ui| speed::section(ui, view));
}
_ => {
// One column: the phone's order, each panel as tall as what it holds.
single(ui, "Problems", |ui| problems::section(ui, view));
single(ui, "Where compiles went", |ui| where_went::section(ui, view));
single(ui, "Why compiles were not cacheable", |ui| where_went::reasons(ui, view));
single(ui, "By language", |ui| where_went::languages(ui, view));
single(ui, "Over time", |ui| {
overtime::section(ui, view, hidden_languages, theme::drawing::CHART_HEIGHT)
});
single(ui, "Speed", |ui| speed::section(ui, view));
}
}
extras(ui, view);
let open = ui
.ctx()
.data_mut(|data| data.get_temp::<bool>(egui::Id::unique("raw-counters-open")))
.unwrap_or(true);
let full = style::span_width(ui, columns, columns);
let [rect] = row(ui, raw::height(view, full, open), &[columns]).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());
let per_row = columns.min(view.extras.len()).max(1);
for line in view.extras.chunks(per_row) {
let spans: Vec<usize> = 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_PADDING * 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>], f64)>,
hover: Option<String>,
}
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);
let value = egui::Label::new(
egui::RichText::new(&self.value)
.font(theme::number_font(self.size))
.color(self.color),
)
.truncate();
ui.add(value.sense(egui::Sense::hover())).on_hover_text(&self.value);
ui.add(egui::Label::new(theme::small(ui, self.caption.clone())).truncate());
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<Option<f64>> = view
.buckets
.iter()
.map(|bucket| (!bucket.gap).then(|| overtime::hit_rate(bucket.hits, bucket.misses)).flatten())
.collect();
let saved: Vec<Option<f64>> = 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) => p.bad,
Some(sccache_dash_api::Severity::Warning) => p.warn,
None => p.text,
};
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();
let rect = egui::Rect::from_min_size(
ui.cursor().min,
egui::vec2(width, theme::layout::HEADLINE_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 spacing = theme::space::PANEL_GAP;
// Side by side where there is room; one under another on a phone.
let side_by_side = width >= 600.0;
let columns = if side_by_side { 3.0 } else { 1.0 };
let column = (width - spacing * (columns - 1.0)) / columns;
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: theme::hit_rate_color(totals.hit_rate(), p),
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(),
};
// 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.text,
caption: "saved (rough)".into(),
small,
small2,
trend: Some((&saved, saved_top)),
hover: Some(view.time_saved.note.clone()),
};
let third = Figure {
value: if problems == 1 {
"1 problem".into()
} else if problems == 0 {
"No problems".into()
} else {
format!("{} problems", fmt::count(problems as u64))
},
size: theme::px::CARD_NUMBER,
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,
};
if side_by_side {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = spacing;
draw(ui, first);
draw(ui, second);
draw(ui, third);
});
} else {
draw(ui, first);
draw(ui, second);
draw(ui, third);
}
style::rule(ui);
ui.add_space(theme::space::PANEL_GAP);
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(theme::small(ui, 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 >= theme::state::CACHE_FULL { p.bad } else { p.from_cache };
style::meter(ui, theme::drawing::USAGE_BAR, full, color);
}
},
);
ui.allocate_rect(taken, egui::Sense::hover());
ui.add_space(theme::space::PANEL_GAP);
}