Compare commits

..
28 Commits
Author SHA1 Message Date
swaitsandClaude Opus 5.5 3a2bcefd38 Redesign the page as an instrument panel: hairline panels, amber hero band, counter strip, two-column grid
Dark charcoal with one amber accent, a derived light theme, the problems list (click to open) inside the hero, raw counters collapsed by default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 09:14:58 -07:00
swaitsandClaude Fable 5.2 06abc4de80 Speed panel: say the time is for one crate's compile, not a whole build
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 18:47:40 -07:00
swaitsandClaude Fable 5.2 e3b56cb213 Never start sccache unless asked; compact reasons panel
A server started from the dashboard has the dashboard's environment, not
the builds'. It came up with the 10 GB default beside a 250 GB cache and
sccache trimmed the cache. Starting is now opt-in
(SCCACHE_DASH_START_SCCACHE=1) and the README says why.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 18:32:20 -07:00
swaitsandClaude Fable 5.2 c2b07734c6 Merge compact reasons panel: one line per reason, click to open
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 18:26:16 -07:00
swaitsandClaude Sonnet 5.5 30643390a7 Reasons: one line each, click to open; stack the small panels beside tall reasons
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 18:23:28 -07:00
swaitsandClaude Fable 5.2 0759cbaa25 just shots: screenshots of the whole page at the 3, 2 and 1 column widths
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 18:08:13 -07:00
swaitsandClaude Fable 5.2 29e5103648 Merge scroll fix: a row scrolled above the window ends at its own bottom
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 18:02:52 -07:00
swaitsandClaude Sonnet 5.5 9630b96c1b Fix the page growing while scrolled: close panel rows at their own bottom
end_row folded the panels' bottoms from 0.0, so a row whose bottom was above
the top of the window (negative screen y while scrolled) was closed at y=0.
Everything after it was placed from there, the scroll content grew by the
scroll offset, and the scroll bar kept shrinking at the bottom. The lowest
bottom is now a plain function in fmt with a native test.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 18:02:00 -07:00
swaitsandClaude Fable 5.2 f08f4655e4 Shorten the low-hit-rate warning; the fix lives in the reasons panel
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 17:51:30 -07:00
swaitsandClaude Fable 5.2 a8c69567b4 Merge hit-rate advice: what each not-cacheable reason means and what to change
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 17:46:17 -07:00
swaitsandClaude Sonnet 5.5 0f4df265a5 Say what each not-cacheable reason means and what to change; explain a low Rust hit rate
Each reason now carries a plain name, meaning, action and a fixable flag (checked
against sccache 0.18.0), shown with its count in the reasons panel, fixable first.
The low-hit-rate problem names the fixable loss and the Rust hash-key inputs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 17:45:38 -07:00
swaitsandClaude Fable 5.2 4a1dfadfb0 Add a favicon: a gauge in the page's colours
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 17:45:20 -07:00
swaitsandClaude Fable 5.2 3ede855fbb Fix the All languages box: ticking it shows every language again
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 17:27:13 -07:00
swaitsandClaude Fable 5.2 3e76fad51f README: say plainly what it is; it does start sccache
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 15:21:19 -07:00
swaitsandClaude Fable 5.2 0cb8206d43 README: screenshots of the dashboard
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 15:17:07 -07:00
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
swaits 03ffdf887a Merge page redesign: panel grid, instrument-panel theme, Inter and JetBrains Mono 2026-11-28 13:32:53 -07:00
swaits a7d836d45a Redesign the page: a grid of panels with an instrument-panel look
Every colour, size, spacing and font now lives in crates/ui/src/theme.rs.
At 1100 px and wider the page is three columns of panels, at 700 px two,
below that one: a toolbar with the range as one segmented control, a
headline panel, six stat cards in one row, three panels side by side,
then Over time beside Speed, then Raw counters as key/value lines.

The type is Inter and JetBrains Mono (SIL Open Font License, licence
files beside the fonts). Tables size their columns to what they hold,
charts keep their time labels inside the plot and tint unrecorded time,
and the hit-rate bars leave the language table where there is no room.

Behaviour is unchanged: ranges, refresh, theme switch, Copy summary,
Export JSON, Zero stats with its question, the language filter and the
remembered settings work as before.
2026-11-28 13:31:51 -07:00
swaits 72fcf8f976 Merge page polish: full-range charts, even cards, aligned tables 2026-11-28 12:49:48 -07:00
swaits 73c8138072 Page polish from the live service
- Both charts always span exactly the selected range, edge to edge. Time
  nothing was recorded in is shaded and labelled once, and each chart's
  key is drawn under the chart instead of over the data.
- The time saved says "not enough data yet" or "nothing saved yet"
  when nothing can be counted, and a saving under a second reads
  "under 1 s", never in milliseconds.
- The six cards are exact boxes of one size, so their tops line up.
- Tables have headed columns at fixed shares of the width, text left and
  numbers right; each row is one rectangle with a place for every cell.
- The cache usage bar has an outlined track.
- When the server can't be reached, the notice is drawn over the page, so
  what is on screen keeps its place and height.
2026-11-28 12:49:21 -07:00
swaits d7351a5d5e Merge fix: history survives a restart; first histogram is immediate 2026-11-28 12:34:57 -07:00
swaitsandClaude Sonnet 5.5 c56aaefa72 History: resume the saved tracker at start; first build observations draw at once
The polling task never loaded the tracker the last run saved, so every
restart began again from a baseline and dropped what had not yet reached a
row. The empty bootstrap drawn at the first poll also started the one-minute
wait for the first real observations.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-28 12:34:30 -07:00
swaitsandClaude Fable 5.2 bcc178330b Lock file with the page crate; ignore local agent notes
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-28 12:24:58 -07:00
swaits f277737e12 Merge page: egui dashboard for the browser 2026-11-28 12:14:19 -07:00
swaits 46b8dcf274 Hit-rate chart: a mark every quarter, so the axis reads 0% to 100% 2026-11-28 12:13:45 -07:00
swaits dc876b5a5c Dashboard page: fit the page, five shares, build-time histograms
- Built is the miss count, as sccache counts timeouts, cache errors and
  forced recaches inside it. The bar under the headline has five shares
  that add up to every compiler call and always to 100%; what happened
  inside the built share is one line under the bar.
- The time saved shows its 90% range in small print under the figure.
- Speed gains "How long builds take, by language": one fixed-height
  histogram per language on a shared log scale of build time, with the
  mean, median and p90 marked.
- The api crate's Range helpers replace the page's own copies.
- Drawing is built only for the browser, so the tests (and the rest of
  the crate) build anywhere without eframe's native backends.
- Tables are drawn row by row; egui's Grid lost its rows when a cell
  held more than a plain widget. Fold-away bodies are held to the width
  of the page, and the charts fit their data every frame.
- mise.toml takes trunk 0.22.2 as a release binary; building it from
  source took over half an hour.
2026-11-28 12:10:01 -07:00
swaits c589b7c868 Merge branch 'main' into t3/dashboard-ui-page 2026-11-28 11:41:03 -07:00
swaits b80749ebb5 Dashboard page for sccache-dash (crates/ui)
An eframe/egui page compiled to WebAssembly with trunk. It draws the one
View the server sends: controls on top, three big figures, six cards, and
the collapsible sections Problems, Where compiles went, Over time, Speed,
Extras and Raw counters. The range, refresh interval and theme are
remembered between visits with eframe storage.

mise.toml names trunk 0.22.2 as the build tool.
2026-11-28 11:30:54 -07:00
39 changed files with 7067 additions and 57 deletions

No files matched your search

+1
View File
@@ -1,3 +1,4 @@
target/ target/
dist/ dist/
.sisi/ .sisi/
AGENTS.md
Generated
+2185 -15
View File
File diff suppressed because it is too large. Load diff
+35 -8
View File
@@ -1,11 +1,30 @@
# sccache-dash # sccache-dash
A small Linux program in the manner of Syncthing: one binary that watches the local Is [sccache](https://github.com/mozilla/sccache) actually saving you time? sccache-dash answers
[sccache](https://github.com/mozilla/sccache) compiler cache, remembers what it did, and serves that with a dashboard in your browser.
a dashboard for it at <http://127.0.0.1:8226>. It listens on this machine only.
It asks sccache for its counters every 10 seconds, works out hit rates, time saved and what looks It is one small Linux program. It runs in the background, reads sccache's counters every 10
wrong, and sends the page one `View` to draw (the contract is `crates/api`). seconds, keeps 30 days of history, and shows the result at <http://127.0.0.1:8226>. Only the
machine it runs on can open that page.
The page shows, for the last hour, 24 hours, 7 days or 30 days:
- how many compiles came from the cache, overall and per language
- roughly how much time that saved, with a 90% range
- what looks wrong: cache errors, timeouts, a language that rarely hits, a cache close to full
- where the other compiles went, and why some could not be cached
- how long a cache hit takes compared with a build, and how build times are spread
## What it looks like
![The dashboard on a wide screen, dark](docs/screenshots/desktop-dark.png)
<table>
<tr>
<td width="72%"><img src="docs/screenshots/desktop-light.png" alt="The dashboard on a wide screen, light"></td>
<td><img src="docs/screenshots/phone-dark.png" alt="The dashboard at phone width, dark"></td>
</tr>
</table>
## Install ## Install
@@ -55,9 +74,17 @@ reading ever is a baseline and counts for nothing.
## Notes on sccache ## Notes on sccache
While sccache's server is running, being asked for its stats every 10 seconds keeps it from its sccache-dash never starts or stops sccache's server by itself. When none is running it shows
10-minute idle shutdown. When it is not running, `sccache --show-stats` does not start it (it "not running"; sccache starts its own server on your next build, with your build's settings.
prints empty counters) and neither does this program; the next compile starts it, as usual.
To have sccache-dash start the server when none is running, set `SCCACHE_DASH_START_SCCACHE=1`
in its environment. Be careful with this: a server started that way gets sccache-dash's
environment, not your build's. If your cache size or folder is set only in your build's
environment, the server comes up with sccache's defaults, and sccache deletes cache entries
until the cache fits the 10 GB default.
While sccache-dash runs, sccache's server stays up: being asked for its stats every 10 seconds
keeps it from shutting itself down after 10 idle minutes.
## Licence ## Licence
+19 -2
View File
@@ -78,8 +78,9 @@ pub struct View {
pub build_times: Vec<BuildTimes>, pub build_times: Vec<BuildTimes>,
/// Sorted by hits + misses, largest first. /// Sorted by hits + misses, largest first.
pub languages: Vec<Language>, pub languages: Vec<Language>,
/// Why compiles were not cacheable, largest first, e.g. ("crate-type", 562). /// Why compiles were not cacheable: reasons you can fix first, then expected ones,
pub not_cached: Vec<(String, u64)>, /// each largest first.
pub not_cached: Vec<NotCached>,
/// Oldest first, evenly spaced, at most 120. /// Oldest first, evenly spaced, at most 120.
pub buckets: Vec<Bucket>, pub buckets: Vec<Bucket>,
/// Most serious first. Empty means no problems. /// Most serious first. Empty means no problems.
@@ -92,6 +93,22 @@ pub struct View {
pub summary_markdown: String, pub summary_markdown: String,
} }
/// One reason sccache gave for not caching a compile, with what to do about it.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct NotCached {
/// Exactly as sccache words it, e.g. "crate-type".
pub reason: String,
pub count: u64,
/// A plain name, e.g. "Incremental compilation is on".
pub name: String,
/// One sentence on what the reason means.
pub meaning: String,
/// What to change, or why nothing needs changing.
pub action: String,
/// True when a setting you control would make these compiles cacheable.
pub fixable: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum Status { pub enum Status {
/// Compiles arrived in the last five minutes. /// Compiles arrived in the last five minutes.
+289
View File
@@ -0,0 +1,289 @@
//! What each "not cacheable" reason means and what to do about it.
//!
//! Every statement here was checked against the sccache 0.18.0 source (the file and line
//! of the code that produces each reason is beside its entry) and, where a command is
//! named, by running it. A reason that is not listed is shown as sccache words it, with
//! "sccache does not say more": we do not guess.
use sccache_dash_api::NotCached;
/// What we know about one reason.
pub struct Advice {
pub name: String,
pub meaning: String,
pub action: String,
pub fixable: bool,
}
fn entry(name: &str, meaning: &str, action: &str, fixable: bool) -> Advice {
Advice {
name: name.to_owned(),
meaning: meaning.to_owned(),
action: action.to_owned(),
fixable,
}
}
/// The advice for `reason`, exactly as sccache's "Non-cacheable reasons" prints it.
pub fn advise(reason: &str) -> Advice {
let expected = |name: &str, meaning: &str, why: &str| {
entry(name, meaning, &format!("Nothing to do, this is expected. {why}"), false)
};
match reason {
// rust.rs:1208 `("incremental", _) => cannot_cache!("incremental")`
"incremental" => entry(
"Incremental compilation is on",
"rustc was told to compile incrementally (-C incremental=...), and sccache 0.18.0 never caches those compiles; its own note says rustc in incremental mode is likely to be faster than fetching from the cache.",
"To cache them, turn incremental off: set CARGO_INCREMENTAL=0 in the environment, or incremental = false under [profile.dev] in Cargo.toml, or incremental = false under [build] in ~/.cargo/config.toml. The trade-off: incremental makes rebuilds of your own crates faster, while the cache helps clean builds and dependency builds.",
true,
),
// rust.rs:1187 and rust.rs:1298: only lib, rlib and staticlib are cached.
"crate-type" => expected(
"Programs and libraries that get linked",
"sccache only caches the crate types lib, rlib and staticlib. Anything else (bin, which includes build scripts and test programs, plus proc-macro, dylib and cdylib), or a call with no crate type, is not cached because rustc runs the system linker and sccache cannot know all of the linker's inputs.",
"Cargo builds each of these in every project, and they cannot be cached.",
),
// rust.rs:1026 `flag!("-", TooHardFlag)`, gcc.rs:190
"-" => expected(
"Source read from standard input",
"The compiler was given a bare - (read the source from standard input), which sccache does not cache.",
"Cargo makes one such call per run to ask rustc about the target it builds for.",
),
// rust.rs:1062 `take_arg!("-o", ..., TooHardPath)`; rust.rs doc: "We don't support `-o file`"
"-o" => entry(
"rustc called with -o",
"rustc was given -o <file>, which sccache 0.18.0 does not cache; it needs --out-dir (cargo passes that for normal builds).",
"Nothing to change in sccache. The tool that called rustc directly would have to use --out-dir instead.",
false,
),
// rust.rs:1280 req!(input) (macro at 1269-1276). Seen in the log as CannotCache(missing input): ["-vV"].
"missing input" => expected(
"rustc call with no source file",
"A rustc call had no source file on its command line, so there was nothing to cache.",
"Cargo starts every run with `rustc -vV` to read the compiler's version, and that is counted here.",
),
// rust.rs:1282 req!(output_dir)
"missing output_dir" => expected(
"rustc call without --out-dir",
"A rustc call had no --out-dir, which sccache requires.",
"It comes from the tool that called rustc; cargo's normal builds pass --out-dir.",
),
// rust.rs:1283 req!(emit)
"missing emit" => expected(
"rustc call without --emit",
"A rustc call had no --emit, which sccache requires.",
"It comes from the tool that called rustc; cargo's normal builds pass --emit.",
),
// rust.rs:1284 req!(crate_name)
"missing crate_name" => expected(
"rustc call without --crate-name",
"A rustc call had no --crate-name, which sccache requires.",
"It comes from the tool that called rustc; cargo's normal builds pass --crate-name.",
),
// rust.rs:1173
"more than one --emit" => expected(
"rustc call with --emit given twice",
"rustc was given --emit more than once, which sccache does not handle.",
"It comes from the tool that called rustc.",
),
// rust.rs:1303 ALLOWED_EMIT = link, metadata, dep-info
"unsupported --emit" => expected(
"rustc asked for extra output",
"rustc was asked to emit something other than link, metadata and dep-info (for example asm or llvm-ir), which sccache does not cache.",
"Those outputs were asked for on purpose.",
),
// rust.rs:1198
"extra-filename" => expected(
"-C extra-filename without a value",
"rustc was given -C extra-filename with no value, which sccache cannot use.",
"It comes from the tool that called rustc.",
),
// rust.rs:1232 ArgTarget::Unsure, rust.rs:955-980
"target unsure" => entry(
"Ambiguous --target",
"The --target value is a plain name, but a file with that name plus .json exists, so sccache cannot tell whether a built-in target or your target file is meant.",
"Pass the target file by its path ending in .json (--target path/to/target.json); sccache then hashes the file's contents.",
true,
),
// rust.rs:1048 `take_arg!("--sysroot", ..., TooHardPath)`
"--sysroot" => entry(
"rustc given --sysroot",
"rustc was given --sysroot, which sccache 0.18.0 does not cache.",
"If it comes from RUSTFLAGS or build.rustflags and you do not need a custom sysroot, remove it.",
true,
),
// rust.rs:1248, gcc.rs:666, msvc.rs:791
"multiple input files" => entry(
"Several source files in one compiler call",
"One compiler call named more than one source file, and sccache caches only one source file per call.",
"If your build passes several files to one compiler call, change it to compile one file per call.",
true,
),
// gcc.rs:362 and diab.rs:206
"@" => expected(
"Option value starting with @",
"An option's value began with @: an @file that sccache could not read or expand, or one attached straight to an option. sccache gives up on both.",
"It comes from how the build passes its flags.",
),
// gcc.rs:466
"-x" => entry(
"Unknown language after -x",
"The call said -x <language> with a language sccache does not know.",
"Use a language sccache knows (c, c++, objective-c, objective-c++, assembler, assembler-with-cpp, cu, cuda, hip, or a header kind) or drop -x.",
true,
),
// gcc.rs:472
"multiple different -arch, and SCCACHE_CACHE_MULTIARCH not set" => entry(
"Several -arch values in one call",
"The call had more than one different -arch, and sccache only caches that when SCCACHE_CACHE_MULTIARCH is set.",
"Set SCCACHE_CACHE_MULTIARCH=1 in the environment sccache's server starts with.",
true,
),
// gcc.rs:674, msvc.rs:802
"no input file" => expected(
"C/C++ call with no source file",
"The compiler call had no source file, so there was nothing to cache.",
"It comes from the tool that called the compiler.",
),
// gcc.rs:688, msvc.rs:799
"unknown source language" => entry(
"Source file type not recognised",
"sccache could not tell the language from the file's extension and the call had no -x.",
"Give the file a standard extension, or add -x c or -x c++ to the call.",
true,
),
// gcc.rs:414
"unknown module output format" => expected(
"Unknown clang module output option",
"A clang module-output option had a value sccache does not understand.",
"Only clang modules builds do this.",
),
// gcc.rs:593-604
"Can't handle complex arguments through clang"
| "Can't handle Raw arguments with -Xclang"
| "Can't handle UnknownFlag arguments with -Xclang" => expected(
"Complicated -Xclang options",
"The call passes options through -Xclang that sccache cannot follow.",
"Remove the -Xclang options if you do not need them.",
),
// msvc.rs:610, msvc.rs:911, msvc.rs:831
"output to nul" | "shared pdb" | "invalid input file" => expected(
"Visual C++ call sccache cannot cache",
"The Visual C++ call writes its output to nul, uses a program database file shared by every compile in the folder (-Zi or -ZI without -Fd), or has an input path with no file name; sccache caches none of these.",
"These come from the call's own options.",
),
// gcc.rs:201-214 TooHardFlag: preprocess-only and dependency-only calls
"-E" | "-M" | "-MM" | "-P" => expected(
"Preprocess-only or dependency-only call",
"The call only preprocesses the source or only writes dependency rules (-E, -M, -MM, -P), so it produces no object file; sccache lists these options as too hard to cache.",
"Your build tool runs these calls on purpose.",
),
// gcc.rs:352, rust.rs:1147, msvc.rs:590
"argument parse" => entry(
"A compiler option sccache could not read",
"sccache could not parse one of the compiler's arguments.",
"sccache does not say more in its counters; run the server with SCCACHE_LOG=debug to see the call.",
false,
),
// gcc.rs:375, clang.rs:192-295, msvc.rs:593: the reason is the option's own name.
other if other.starts_with('-') && other.len() > 1 => entry(
&format!("Option {other} is never cached"),
&format!(
"The compiler call contains {other}, which sccache's option table lists as too hard to cache, so every call with it runs uncached."
),
"If you do not need the option, remove it from the build's flags.",
true,
),
other => entry(
other,
"sccache does not say more.",
"",
false,
),
}
}
/// Dress counted reasons with their advice: fixable ones first, then expected ones, each
/// largest first.
pub fn describe(reasons: &[(String, u64)]) -> Vec<NotCached> {
let mut out: Vec<NotCached> = reasons
.iter()
.map(|(reason, count)| {
let a = advise(reason);
NotCached {
reason: reason.clone(),
count: *count,
name: a.name,
meaning: a.meaning,
action: a.action,
fixable: a.fixable,
}
})
.collect();
out.sort_by(|a, b| {
b.fixable
.cmp(&a.fixable)
.then_with(|| b.count.cmp(&a.count))
.then_with(|| a.reason.cmp(&b.reason))
});
out
}
/// How many compiles were lost to reasons that can be fixed, and the biggest of them.
pub fn fixable_loss(reasons: &[NotCached]) -> Option<(u64, &NotCached)> {
let top = reasons.iter().filter(|r| r.fixable).max_by_key(|r| r.count)?;
Some((reasons.iter().filter(|r| r.fixable).map(|r| r.count).sum(), top))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn incremental_says_how_to_turn_it_off_and_what_it_costs() {
let a = advise("incremental");
assert!(a.fixable);
assert!(a.action.contains("CARGO_INCREMENTAL=0"));
assert!(a.action.contains("[profile.dev]"));
assert!(a.action.contains("[build]"));
assert!(a.action.contains("trade-off"));
}
#[test]
fn crate_type_is_expected_and_names_what_is_cached() {
let a = advise("crate-type");
assert!(!a.fixable);
assert!(a.action.starts_with("Nothing to do"));
assert!(a.meaning.contains("lib, rlib and staticlib"));
}
#[test]
fn an_unknown_reason_is_shown_as_it_came() {
let a = advise("something new in 0.19");
assert_eq!(a.name, "something new in 0.19");
assert_eq!(a.meaning, "sccache does not say more.");
assert!(!a.fixable);
}
#[test]
fn an_option_name_is_a_fixable_reason_but_the_known_dashes_are_not() {
assert!(advise("-fplugin").fixable);
assert!(!advise("-").fixable);
assert!(!advise("-o").fixable);
}
#[test]
fn fixable_reasons_come_first_then_the_biggest() {
let out = describe(&[
("crate-type".to_owned(), 1548),
("-".to_owned(), 156),
("incremental".to_owned(), 1642),
("multiple input files".to_owned(), 63),
]);
let order: Vec<&str> = out.iter().map(|r| r.reason.as_str()).collect();
assert_eq!(order, ["incremental", "multiple input files", "crate-type", "-"]);
let (lost, top) = fixable_loss(&out).unwrap();
assert_eq!((lost, top.reason.as_str()), (1705, "incremental"));
assert!(fixable_loss(&out[2..]).is_none());
}
}
+21 -2
View File
@@ -34,10 +34,16 @@ pub struct Config {
pub sccache: OsString, pub sccache: OsString,
/// The SQLite file the history is saved in. /// The SQLite file the history is saved in.
pub history: PathBuf, pub history: PathBuf,
/// Whether to start sccache's server when none is listening. Off unless asked for: a
/// server started from here has this program's environment, not the builds', so it can
/// come up with another cache size or folder, and sccache trims the cache to the size
/// it is started with.
pub start_sccache: bool,
} }
impl Config { impl Config {
/// `SCCACHE_DASH_SCCACHE` names the sccache command (`sccache` when unset); the history /// `SCCACHE_DASH_SCCACHE` names the sccache command (`sccache` when unset);
/// `SCCACHE_DASH_START_SCCACHE=1` lets it start sccache's server; the history
/// lives in `$XDG_DATA_HOME/sccache-dash/history.db`. /// lives in `$XDG_DATA_HOME/sccache-dash/history.db`.
pub fn from_env() -> Result<Config, String> { pub fn from_env() -> Result<Config, String> {
let sccache = std::env::var_os("SCCACHE_DASH_SCCACHE").unwrap_or_else(|| "sccache".into()); let sccache = std::env::var_os("SCCACHE_DASH_SCCACHE").unwrap_or_else(|| "sccache".into());
@@ -46,6 +52,7 @@ impl Config {
Ok(Config { Ok(Config {
sccache, sccache,
history: dir.join("sccache-dash").join("history.db"), history: dir.join("sccache-dash").join("history.db"),
start_sccache: std::env::var_os("SCCACHE_DASH_START_SCCACHE").is_some_and(|v| v == "1"),
}) })
} }
} }
@@ -194,6 +201,8 @@ pub struct Task {
/// When sccache's server was last tried to start, and why it is still not running. /// When sccache's server was last tried to start, and why it is still not running.
started_at: Option<i64>, started_at: Option<i64>,
start_error: Option<String>, start_error: Option<String>,
/// Whether the totals the last run remembered have been put back into the shared state.
resumed: bool,
} }
impl Task { impl Task {
@@ -217,6 +226,7 @@ impl Task {
builds: Builds::new(), builds: Builds::new(),
started_at: None, started_at: None,
start_error: None, start_error: None,
resumed: false,
} }
} }
@@ -240,6 +250,12 @@ impl Task {
(Probe::NotRunning, false) => {} (Probe::NotRunning, false) => {}
} }
let mut state = app.lock(); let mut state = app.lock();
if !self.resumed {
// Carry on where the last run stopped: its running totals are the base that the work
// not yet in a row is counted from, so a restart neither drops it nor counts it twice.
self.resumed = true;
state.tracker = self.history.tracker();
}
state.client_version = version; state.client_version = version;
match read { match read {
Ok((text, snapshot)) => { Ok((text, snapshot)) => {
@@ -290,9 +306,12 @@ impl Task {
} }
} }
/// Starts sccache's server when none is listening, at most once a minute. `Err` says why /// Starts sccache's server when none is listening and that was asked for, at most once a minute. `Err` says why
/// there is none, including when an earlier attempt is still being waited out. /// there is none, including when an earlier attempt is still being waited out.
fn start_server(&mut self, app: &App, now: i64) -> Result<(), String> { fn start_server(&mut self, app: &App, now: i64) -> Result<(), String> {
if !app.cfg.start_sccache {
return Err("no sccache server is running; your next build starts it".to_owned());
}
if let Some(when) = self.started_at { if let Some(when) = self.started_at {
if now - when < START_EVERY { if now - when < START_EVERY {
return Err(self return Err(self
+1
View File
@@ -1,6 +1,7 @@
//! The server half of sccache-dash: it asks sccache for its counters, keeps their history and //! The server half of sccache-dash: it asks sccache for its counters, keeps their history and
//! serves the page that draws them. //! serves the page that draws them.
pub mod advice;
pub mod app; pub mod app;
pub mod history; pub mod history;
pub mod http; pub mod http;
+66 -15
View File
@@ -2,11 +2,12 @@
//! after every poll and kept; a request never waits for the database. //! after every poll and kept; a request never waits for the database.
use sccache_dash_api::{ use sccache_dash_api::{
Bucket, BuildTimes, Language, Problem, Range, Server, Severity, Status, TimeSaved, Timing, View, Bucket, BuildTimes, Language, NotCached, Problem, Range, Server, Severity, Status, TimeSaved, Timing, View,
}; };
use sccache_dash_stats::{LanguageHits, Observation, Resampled, Saved}; use sccache_dash_stats::{LanguageHits, Observation, Resampled, Saved};
use serde_json::Value; use serde_json::Value;
use crate::advice;
use crate::app::State; use crate::app::State;
use crate::history::{BucketLangs, BucketRow, History, Row}; use crate::history::{BucketLangs, BucketRow, History, Row};
use crate::pretty; use crate::pretty;
@@ -147,7 +148,11 @@ impl Builds {
self.draws = Resampled::new(&obs); self.draws = Resampled::new(&obs);
self.times = times; self.times = times;
self.stamp = Some(stamp); self.stamp = Some(stamp);
self.drawn_at = Some(now); // Drawing nothing is free, so it does not start the minute's wait: the first
// observations are drawn at the very next poll.
if stamp.0 > 0 {
self.drawn_at = Some(now);
}
} }
/// Time saved for one range's hits, from the draws already made. /// Time saved for one range's hits, from the draws already made.
@@ -429,6 +434,34 @@ fn buckets(chart: Chart<'_>, now: i64, builds: &Builds, hit_read: f64, live: boo
out out
} }
/// What a low hit rate means and what to try. Everything said about why a Rust compile misses
/// is what sccache 0.18.0's hash key for Rust (src/compiler/rust.rs, `generate_hash_key`) is
/// made of, and was checked by building the same crate twice, in two directories, through a
/// throwaway server.
fn low_hit_rate_detail(name: &str, hits: u64, n: u64, reasons: &[NotCached]) -> String {
let mut text = format!(
"Only {}% of {} {name} compiles came from the cache.",
pretty::pct(hits as f64 / n as f64),
pretty::thousands(n)
);
if let Some((lost, top)) = advice::fixable_loss(reasons) {
text.push_str(&format!(
" Another {} were skipped for reasons you can fix, mostly \"{}\" ({}): see \"Why compiles were not cacheable\".",
pretty::thousands(lost),
top.name,
pretty::thousands(top.count),
));
}
if name == "Rust" {
text.push_str(
" A Rust compile misses when the folder it is built in, the compiler version, the flags or a CARGO_* variable differ from last time, so the same crate built in two folders (two git worktrees, or a different CARGO_TARGET_DIR variable) is built twice.",
);
} else {
text.push_str(" sccache's counters do not say why a compile missed.");
}
text
}
fn problems(c: &Counters, server: &Server) -> Vec<Problem> { fn problems(c: &Counters, server: &Server) -> Vec<Problem> {
let t = &c.totals; let t = &c.totals;
let (mut errors, mut warnings) = (Vec::new(), Vec::new()); let (mut errors, mut warnings) = (Vec::new(), Vec::new());
@@ -488,15 +521,12 @@ fn problems(c: &Counters, server: &Server) -> Vec<Problem> {
.map(|(name, v)| (name, v[0], v[0] + v[1])) .map(|(name, v)| (name, v[0], v[0] + v[1]))
.collect(); .collect();
low.sort_by(|a, b| (a.1 * b.2).cmp(&(b.1 * a.2)).then_with(|| a.0.cmp(b.0))); low.sort_by(|a, b| (a.1 * b.2).cmp(&(b.1 * a.2)).then_with(|| a.0.cmp(b.0)));
let reasons = advice::describe(&c.not_cached);
for (name, hits, n) in low { for (name, hits, n) in low {
warnings.push(problem( warnings.push(problem(
Severity::Warning, Severity::Warning,
format!("{name} hit rate {}%", pretty::pct(hits as f64 / n as f64)), format!("{name} hit rate {}%", pretty::pct(hits as f64 / n as f64)),
format!( low_hit_rate_detail(name, hits, n, &reasons),
"Only {}% of {} {name} compiles came from the cache, so most were rebuilt; a different toolchain, compiler flags or environment makes sccache miss, so compare those between two builds.",
pretty::pct(hits as f64 / n as f64),
pretty::thousands(n)
),
)); ));
} }
if let (Some(size), Some(max)) = (server.cache_size, server.max_cache_size) { if let (Some(size), Some(max)) = (server.cache_size, server.max_cache_size) {
@@ -674,8 +704,7 @@ fn compute(
.cmp(&(a.hits + a.misses)) .cmp(&(a.hits + a.misses))
.then_with(|| a.name.cmp(&b.name)) .then_with(|| a.name.cmp(&b.name))
}); });
let mut not_cached = counters.not_cached.clone(); let not_cached = advice::describe(&counters.not_cached);
not_cached.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
let mut view = View { let mut view = View {
range: Some(range), range: Some(range),
@@ -1048,11 +1077,15 @@ mod tests {
errors: 0 errors: 0
} }
); );
let order: Vec<&str> = v.not_cached.iter().map(|r| r.reason.as_str()).collect();
assert_eq!( assert_eq!(
v.not_cached[0], order,
("crate-type".to_owned(), 621), ["incremental", "multiple input files", "crate-type", "-o", "-", "missing input", "missing emit"],
"largest reason first" "reasons you can fix first, then the expected ones, each largest first"
); );
assert_eq!((v.not_cached[0].count, v.not_cached[0].fixable), (105, true));
assert_eq!(v.not_cached[2].count, 621);
assert!(!v.not_cached[2].fixable);
assert_eq!(v.raw, serde_json::from_str::<Value>(LIVE).unwrap()); assert_eq!(v.raw, serde_json::from_str::<Value>(LIVE).unwrap());
} }
@@ -1446,7 +1479,24 @@ mod tests {
); );
assert!(rate(vec![("Rust", [4, 46, 0])]).problems[0] assert!(rate(vec![("Rust", [4, 46, 0])]).problems[0]
.detail .detail
.starts_with("Only 8% of 50 Rust compiles came from the cache, so most were rebuilt;")); .starts_with("Only 8% of 50 Rust compiles came from the cache."));
let detail = seen(
|s| {
s.counters.langs = vec![("Rust".to_owned(), [4, 46, 0])];
s.counters.not_cached = vec![("incremental".to_owned(), 30), ("crate-type".to_owned(), 90)];
},
"0.18.0",
)
.problems[0]
.detail
.clone();
assert!(
detail.contains("Another 30 were skipped for reasons you can fix")
&& detail.contains("\"Incremental compilation is on\" (30)")
&& detail.contains("the folder it is built in")
&& !detail.contains("Programs and libraries"),
"{detail}"
);
assert!( assert!(
rate(vec![("Rust", [19, 30, 0])]).problems.is_empty(), rate(vec![("Rust", [19, 30, 0])]).problems.is_empty(),
"49 compiles is too few to say" "49 compiles is too few to say"
@@ -1541,8 +1591,9 @@ mod tests {
assert!( assert!(
all.problems all.problems
.iter() .iter()
.all(|p| p.detail.split(". ").count() == 1 && p.detail.ends_with('.')), .all(|p| p.detail.ends_with('.')
"each detail is one sentence: {:?}", && (p.title.contains("hit rate") || p.detail.split(". ").count() == 1)),
"each detail is one sentence, except the hit-rate one that says what to change: {:?}",
all.problems all.problems
); );
} }
+195 -15
View File
@@ -91,6 +91,7 @@ esac
Config { Config {
sccache: self.script.clone().into(), sccache: self.script.clone().into(),
history: self.history.clone(), history: self.history.clone(),
start_sccache: true,
} }
} }
} }
@@ -444,6 +445,30 @@ fn old_rows_are_deleted_at_startup() {
); );
} }
#[test]
fn a_missing_sccache_server_is_left_alone_unless_starting_was_asked_for() {
let fake = Fake::new();
fake.down();
let app = App::with_probe(
Config {
start_sccache: false,
..fake.config()
},
fake.probe(),
);
let mut task = Task::memory();
task.poll(&app, NOW);
task.poll(&app, NOW + 120);
let calls = fake.calls();
assert!(!calls.iter().any(|c| c == "--start-server"), "{calls:?}");
assert!(app
.lock()
.error
.as_deref()
.is_some_and(|e| e.contains("your next build starts it")));
}
#[test] #[test]
fn a_missing_sccache_server_is_started_once_then_read() { fn a_missing_sccache_server_is_started_once_then_read() {
let fake = Fake::new(); let fake = Fake::new();
@@ -576,9 +601,10 @@ fn the_bootstrap_is_not_redrawn_on_every_poll_of_a_build_in_flight() {
task.poll(&app, NOW); task.poll(&app, NOW);
assert_eq!(rust_builds(&app), 0, "nothing seen yet"); assert_eq!(rust_builds(&app), 0, "nothing seen yet");
// A build adds one Rust build between every pair of polls. Each is stored at once, but the // A build adds one Rust build between every pair of polls. Each is stored at once. The first
// histogram (and with it the bootstrap) waits for the one-minute beat. // is drawn at the next poll (the empty draw before it started no wait); the rest wait for
for step in 1..6u64 { // the one-minute beat that began with that draw.
for step in 1..7u64 {
fake.answers(&with_more_rust_builds(step)); fake.answers(&with_more_rust_builds(step));
task.poll(&app, NOW + (step as i64) * 10); task.poll(&app, NOW + (step as i64) * 10);
assert_eq!( assert_eq!(
@@ -588,23 +614,23 @@ fn the_bootstrap_is_not_redrawn_on_every_poll_of_a_build_in_flight() {
); );
assert_eq!( assert_eq!(
rust_builds(&app), rust_builds(&app),
0, 1,
"but the bootstrap drawn at the first poll stands (step {step})" "the first draw stands for the minute (step {step})"
); );
} }
fake.answers(&with_more_rust_builds(6));
task.poll(&app, NOW + 60);
assert_eq!(
rust_builds(&app),
6,
"a minute after the last draw, everything seen so far is drawn in"
);
fake.answers(&with_more_rust_builds(7)); fake.answers(&with_more_rust_builds(7));
task.poll(&app, NOW + 70); task.poll(&app, NOW + 70);
assert_eq!( assert_eq!(
rust_builds(&app), rust_builds(&app),
6, 7,
"a minute after the last draw, everything seen so far is drawn in"
);
fake.answers(&with_more_rust_builds(8));
task.poll(&app, NOW + 80);
assert_eq!(
rust_builds(&app),
7,
"and it stands again until the next beat" "and it stands again until the next beat"
); );
} }
@@ -647,7 +673,10 @@ fn a_full_history_costs_few_rows_on_the_second_poll() {
"the first reading is the baseline" "the first reading is the baseline"
); );
let observations = task.history.build_obs_stamp().unwrap().0; let observations = task.history.build_obs_stamp().unwrap().0;
assert_eq!(observations, 4_319, "one for every tenth minute after the baseline"); assert_eq!(
observations, 4_319,
"one for every tenth minute after the baseline"
);
task.poll(&app, NOW); task.poll(&app, NOW);
let first = app.lock().views_rows; let first = app.lock().views_rows;
@@ -662,3 +691,154 @@ fn a_full_history_costs_few_rows_on_the_second_poll() {
let v = app.view(Range::Day); let v = app.view(Range::Day);
assert_eq!(v.buckets.len(), 120); assert_eq!(v.buckets.len(), 120);
} }
/// What sccache prints after `k` more rounds of work: every round adds 3 requests, 2 hits and
/// 1 Rust miss that took 5 s to compile.
fn after_rounds(k: u64) -> String {
let mut v: serde_json::Value = serde_json::from_str(LIVE).unwrap();
let s = &mut v["stats"];
let add = |s: &mut serde_json::Value, key: &str, n: u64| {
s[key] = (s[key].as_u64().unwrap() + n).into();
};
add(s, "compile_requests", 3 * k);
add(s, "requests_executed", k);
add(s, "cache_writes", k);
add(s, "compilations", k);
s["cache_hits"]["counts"]["Rust"] = (229 + 2 * k).into();
s["cache_misses"]["counts"]["Rust"] = (3256 + k).into();
let secs = 25343 + 5 * k;
s["compiler_write_duration"]["secs"] = secs.into();
v.to_string()
}
/// Polls once a `step` seconds from `from` to `to`, the counters rising a round each time.
fn run_polls(
fake: &Fake,
app: &App,
task: &mut Task,
rounds: &mut u64,
span: (i64, i64),
step: i64,
) {
let mut t = span.0;
while t <= span.1 {
fake.answers(&after_rounds(*rounds));
task.poll(app, t);
*rounds += 1;
t += step;
}
}
#[test]
fn a_restart_loses_nothing_and_counts_nothing_twice() {
let fake = Fake::new();
let mut rounds = 0;
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::open(&fake.history, NOW).unwrap();
// Five minutes of polls, every ten seconds, with work in each; the last 30 s after a row.
run_polls(&fake, &app, &mut task, &mut rounds, (NOW, NOW + 330), 10);
let before = app.view(Range::Day);
assert!(before.totals.requests > 0, "{:?}", before.totals);
assert!(
task.history.row_count().unwrap() >= 4,
"a row a minute on disk while it runs, not at the end: {}",
task.history.row_count().unwrap()
);
drop(task);
drop(app);
// The restart: a new process opens the same file and polls once, ten seconds later, with
// the same counters sccache had (no work in between).
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::open(&fake.history, NOW + 340).unwrap();
rounds -= 1;
run_polls(
&fake,
&app,
&mut task,
&mut rounds,
(NOW + 340, NOW + 340),
10,
);
let after = app.view(Range::Day);
assert_eq!(
(after.totals, after.previous),
(before.totals, before.previous),
"a view's totals are the same just before and just after a restart"
);
}
#[test]
fn a_restart_counts_the_work_done_while_it_was_down() {
let fake = Fake::new();
let mut rounds = 0;
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::open(&fake.history, NOW).unwrap();
run_polls(&fake, &app, &mut task, &mut rounds, (NOW, NOW + 200), 10);
let before = app.view(Range::Day).totals.requests;
drop(task);
drop(app);
// sccache went on working for 4 rounds while sccache-dash was stopped.
rounds += 3;
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::open(&fake.history, NOW + 260).unwrap();
run_polls(
&fake,
&app,
&mut task,
&mut rounds,
(NOW + 260, NOW + 260),
10,
);
assert_eq!(
app.view(Range::Day).totals.requests,
before + 4 * 3,
"the difference since the last poll before the stop is counted, once"
);
}
#[test]
fn build_times_show_within_a_minute_of_the_observations() {
let fake = Fake::new();
let mut rounds = 0;
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::open(&fake.history, NOW).unwrap();
// The first poll draws the (empty) bootstrap; the observations come after it.
run_polls(&fake, &app, &mut task, &mut rounds, (NOW, NOW + 600), 10);
let shown = |t: &Task| t.history.build_obs_stamp().unwrap().0;
assert!(shown(&task) >= 50, "observations were recorded");
let times = app.view(Range::Day).build_times;
assert_eq!(times.len(), 1, "Rust has a histogram after ten minutes");
// Stop polling for work: after one more poll a minute on, the newest are in too.
let seen = times[0].compiles;
run_polls(
&fake,
&app,
&mut task,
&mut rounds,
(NOW + 610, NOW + 680),
10,
);
let now = app.view(Range::Day).build_times[0].compiles;
assert!(now > seen, "the histogram keeps up: {seen} then {now}");
}
#[test]
fn the_first_observations_show_at_the_next_poll_not_a_minute_later() {
let fake = Fake::new();
let mut rounds = 0;
let app = App::with_probe(fake.config(), fake.probe());
let mut task = Task::open(&fake.history, NOW).unwrap();
// The first poll draws nothing: there is nothing to draw, and that must not start the
// minute's wait for the first real observations.
run_polls(&fake, &app, &mut task, &mut rounds, (NOW, NOW + 30), 10);
assert!(task.history.build_obs_stamp().unwrap().0 >= 3);
assert_eq!(
app.view(Range::Day).build_times.len(),
1,
"seconds after the first observation, not a minute"
);
}
+33
View File
@@ -0,0 +1,33 @@
[package]
name = "sccache-dash-ui"
description = "Dashboard page for sccache-dash"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
sccache-dash-api = { path = "../api" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# The page is drawn with eframe in the browser for now. A native window would
# open the same `Dashboard`, and needs eframe here with its x11 and wayland features.
[target.'cfg(target_arch = "wasm32")'.dependencies]
eframe = { version = "0.37", default-features = false, features = [
"default_fonts",
"glow",
"persistence",
] }
egui_plot = "0.38"
ehttp = "0.7"
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = [
"Document",
"Element",
"HtmlAnchorElement",
"HtmlCanvasElement",
"Window",
] }
+92
View File
@@ -0,0 +1,92 @@
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION AND CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+93
View File
@@ -0,0 +1,93 @@
Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
+39
View File
@@ -0,0 +1,39 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="dark light" />
<title>sccache dash</title>
<!-- A gauge in the page's own colours. -->
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 32 32%22%3E%3Crect width=%2232%22 height=%2232%22 rx=%227%22 fill=%22%23161a22%22/%3E%3Cpath d=%22M6 22a10 10 0 0 1 20 0%22 fill=%22none%22 stroke=%22%233a4254%22 stroke-width=%224%22 stroke-linecap=%22round%22/%3E%3Cpath d=%22M6 22a10 10 0 0 1 15-8.66%22 fill=%22none%22 stroke=%22%234cc38a%22 stroke-width=%224%22 stroke-linecap=%22round%22/%3E%3Cpath d=%22M16 22l6-8%22 stroke=%22%23e6e9ef%22 stroke-width=%222.5%22 stroke-linecap=%22round%22/%3E%3Ccircle cx=%2216%22 cy=%2222%22 r=%222.5%22 fill=%22%23e6e9ef%22/%3E%3C/svg%3E" />
<link data-trunk rel="rust" data-bin="sccache-dash-ui" />
<style>
/* The page is one canvas that fills the window and scrolls inside itself. */
html,
body {
height: 100%;
height: 100dvh;
margin: 0;
overflow: hidden;
/* The page colour of each theme (crates/ui/src/theme.rs), so nothing flashes while the page loads. */
background: #0e1116;
}
@media (prefers-color-scheme: light) {
html,
body {
background: #f5f6f8;
}
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
}
</style>
</head>
<body>
<canvas id="the_canvas_id"></canvas>
</body>
</html>
+936
View File
@@ -0,0 +1,936 @@
//! 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<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())
}
/// 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::<f32>()
+ 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<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 "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<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 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::<bool>(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<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_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>], f64)>,
/// Instead of a trend line and small print: the problems list.
problems: Option<&'a View>,
hover: Option<String>,
}
/// 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<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 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);
}
+143
View File
@@ -0,0 +1,143 @@
//! The six counters under the headline: one quiet strip, all cells the same size, tops in a line.
use eframe::egui::{self, Color32, Pos2, Rect, RichText};
use sccache_dash_api::{Range, View};
use crate::fmt;
use crate::style;
use crate::theme;
/// The cards in `per_row` per row: six in one row on a wide screen, three in
/// the two-column layout, two on a phone.
pub fn row(ui: &mut egui::Ui, view: &View, per_row: usize) {
let totals = &view.totals;
let previous = view.previous.as_ref();
let range = view.range.unwrap_or(Range::Day);
let p = theme::ui(ui);
let requests = totals.requests;
let cache_errors = totals.errors();
let cards = [
Card {
title: "Cache hits",
count: totals.hits,
color: None,
detail: format!("{} of compiler calls", fmt::share(totals.hits, requests)),
previous: previous.map(|previous| previous.hits),
good_when_up: true,
},
Card {
title: "Cache misses",
count: totals.misses,
color: None,
detail: format!("{} of compiler calls", fmt::share(totals.misses, requests)),
previous: previous.map(|previous| previous.misses),
good_when_up: false,
},
Card {
title: "Timeouts",
count: totals.timeouts,
color: (totals.timeouts > 0).then_some(p.bad),
detail: String::new(),
previous: previous.map(|previous| previous.timeouts),
good_when_up: false,
},
Card {
title: "Cache errors",
count: cache_errors,
color: (cache_errors > 0).then_some(p.bad),
detail: format!(
"{} read · {} write · {} other",
fmt::count(totals.read_errors),
fmt::count(totals.write_errors),
fmt::count(totals.other_errors)
),
previous: previous.map(|previous| previous.errors()),
good_when_up: false,
},
Card {
title: "Compile failures",
count: totals.compile_fails,
color: None,
detail: String::new(),
previous: previous.map(|previous| previous.compile_fails),
good_when_up: false,
},
Card {
title: "Forced recaches",
count: totals.forced_recaches,
color: None,
detail: String::new(),
previous: previous.map(|previous| previous.forced_recaches),
good_when_up: false,
},
];
let per_row = per_row.max(1);
let left = ui.cursor().left();
let mut top = ui.cursor().top();
let width = ui.available_rect_before_wrap().width();
let cell_width = width / per_row as f32;
let height = theme::layout::STRIP_ROW_HEIGHT;
let rule = egui::Stroke::new(1.0, p.border);
ui.painter().hline(left..=left + width, top + 0.5, rule);
for (line_index, line) in cards.chunks(per_row).enumerate() {
if line_index > 0 {
ui.painter().hline(left..=left + width, top + 0.5, egui::Stroke::new(1.0, p.grid));
}
for (index, card) in line.iter().enumerate() {
let change = change(card.count, card.previous, range, card.good_when_up, p);
style::card(
ui,
Rect::from_min_size(Pos2::new(left + index as f32 * cell_width, top), egui::vec2(cell_width, height)),
index == 0,
card.title,
&fmt::count(card.count),
&card.detail,
change,
card.color.unwrap_or(p.text),
);
}
top += height;
}
ui.painter().hline(left..=left + width, top - 0.5, rule);
ui.add_space(top - ui.cursor().top());
ui.add_space(theme::space::PANEL_GAP);
}
struct Card {
title: &'static str,
count: u64,
/// The colour of the count when it is worth a look.
color: Option<Color32>,
/// The line between the count and the comparison.
detail: String,
/// The same count in the period before, when the server has one.
previous: Option<u64>,
/// Whether more of this count is good news.
good_when_up: bool,
}
/// How a count compares with the period before, and the colour that change deserves.
fn change(count: u64, previous: Option<u64>, range: Range, good_when_up: bool, p: &theme::Palette) -> RichText {
let Some(previous) = previous else {
return RichText::new("").font(egui::FontId::proportional(theme::px::SMALL));
};
if previous == 0 {
return small_plain(p, if count == 0 { String::new() } else { "was 0 before".into() });
}
let change = (count as f64 - previous as f64) / previous as f64 * 100.0;
if change.abs() < 0.5 {
return small_plain(p, "no change".into());
}
let better = (change > 0.0) == good_when_up;
RichText::new(format!("{change:+.0}% vs {}", fmt::previous_label(range)))
.font(egui::FontId::proportional(theme::px::SMALL))
.color(if better { p.good } else { p.bad })
}
fn small_plain(p: &theme::Palette, text: String) -> RichText {
RichText::new(text)
.font(egui::FontId::proportional(theme::px::SMALL))
.color(p.muted)
}
+88
View File
@@ -0,0 +1,88 @@
//! The arithmetic of a list of lines that open: which start open, how tall the
//! list is, and whether stacking panels beside it wastes less room. No drawing
//! here, so it is tested natively.
/// A line that opens to show a text beneath it, laid out for a width.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Entry {
/// The line itself.
pub row: f32,
pub open: bool,
/// The first paragraph's height; used only when open.
pub meaning: f32,
/// The second paragraph's height, `None` when there is none; used only when open.
pub action: Option<f32>,
}
/// Whether a line is open: what was clicked, else open when `fixable`.
pub fn is_open(stored: Option<bool>, fixable: bool) -> bool {
stored.unwrap_or(fixable)
}
/// How tall one line is: `gap` between its parts, `pad` under the open text.
pub fn entry_height(entry: &Entry, gap: f32, pad: f32) -> f32 {
if !entry.open {
return entry.row;
}
let action = entry.action.map_or(0.0, |height| gap + height);
entry.row + gap + entry.meaning + action + pad
}
/// How tall the whole list is: its lines and a hairline `separator` tall between them.
pub fn list_height(entries: &[Entry], gap: f32, pad: f32, separator: f32) -> f32 {
let lines: f32 = entries.iter().map(|entry| entry_height(entry, gap, pad)).sum();
lines + entries.len().saturating_sub(1) as f32 * separator
}
/// Whether to stack the panels (`stacked` tall in all) beside a panel `beside` tall rather
/// than put the one `single` panel there: yes when that leaves less empty room.
pub fn stack_beside(single: f32, stacked: f32, beside: f32) -> bool {
(stacked - beside).abs() < (single - beside).abs()
}
#[cfg(test)]
mod tests {
use super::*;
fn entry(open: bool) -> Entry {
Entry { row: 28.0, open, meaning: 45.0, action: Some(30.0) }
}
#[test]
fn only_fixable_lines_start_open() {
assert!(is_open(None, true));
assert!(!is_open(None, false));
}
#[test]
fn a_click_wins_over_the_default() {
assert!(!is_open(Some(false), true));
assert!(is_open(Some(true), false));
}
#[test]
fn a_closed_line_is_one_row_and_an_open_one_adds_its_text() {
assert_eq!(entry_height(&entry(false), 3.0, 8.0), 28.0);
assert_eq!(entry_height(&entry(true), 3.0, 8.0), 28.0 + 3.0 + 45.0 + 3.0 + 30.0 + 8.0);
let no_action = Entry { action: None, ..entry(true) };
assert_eq!(entry_height(&no_action, 3.0, 8.0), 28.0 + 3.0 + 45.0 + 8.0);
}
#[test]
fn a_list_is_its_lines_and_the_hairlines_between() {
let list = [entry(true), entry(false), entry(false)];
assert_eq!(list_height(&list, 3.0, 8.0, 1.0), 117.0 + 28.0 + 28.0 + 2.0);
assert_eq!(list_height(&[], 3.0, 8.0, 1.0), 0.0);
assert_eq!(list_height(&[entry(false)], 3.0, 8.0, 1.0), 28.0);
}
#[test]
fn stacking_is_chosen_only_when_it_fills_the_room_better() {
// Everything closed: the lone panel (244) is close to the list (300); three stacked (500) are not.
assert!(!stack_beside(244.0, 500.0, 300.0));
// Two open: the list (520) is nearer the stack.
assert!(stack_beside(244.0, 500.0, 520.0));
// A tie keeps the simple layout.
assert!(!stack_beside(200.0, 400.0, 300.0));
}
}
+22
View File
@@ -0,0 +1,22 @@
//! Extras: the tables sccache only fills in for some setups, one panel each.
use sccache_dash_api::View;
use crate::style::{self, Cell};
use crate::theme;
pub fn section(ui: &mut eframe::egui::Ui, view: &View) {
for extra in &view.extras {
let rows: Vec<Vec<Cell>> = extra
.rows
.iter()
.map(|(label, value)| {
vec![
Cell::Text(theme::strong(label.clone())),
Cell::Text(theme::number(value.clone())),
]
})
.collect();
style::table(ui, &[], &rows);
}
}
+313
View File
@@ -0,0 +1,313 @@
//! How numbers, durations and times are written on the page.
use sccache_dash_api::Range;
/// How a comparison with the period before is worded, from the range's own
/// label: "previous 24 hours".
pub fn previous_label(range: Range) -> String {
let label = range.label();
format!("previous {}", label.strip_prefix("last ").unwrap_or(label))
}
/// The lowest edge of a row of panels: the largest of their `bottoms`, or
/// `empty` when there are none. The bottoms are screen positions, so they are
/// negative while the row is scrolled above the top of the window.
pub fn lowest(bottoms: impl IntoIterator<Item = f32>, empty: f32) -> f32 {
bottoms.into_iter().reduce(f32::max).unwrap_or(empty)
}
/// Whole-number percentages of `parts` that add up to exactly 100, giving the
/// leftovers of rounding to the largest shares. All zero when nothing is counted.
pub fn shares(parts: &[u64]) -> Vec<u64> {
let total: u64 = parts.iter().sum();
if total == 0 {
return vec![0; parts.len()];
}
let exact: Vec<f64> = parts
.iter()
.map(|part| 100.0 * *part as f64 / total as f64)
.collect();
let mut whole: Vec<u64> = exact.iter().map(|value| value.floor() as u64).collect();
let mut left = 100 - whole.iter().sum::<u64>();
let mut by_fraction: Vec<usize> = (0..parts.len()).collect();
by_fraction.sort_by(|a, b| exact[*b].fract().total_cmp(&exact[*a].fract()));
for index in by_fraction {
if left == 0 {
break;
}
whole[index] += 1;
left -= 1;
}
whole
}
/// How the refresh control names an interval: "Every 10 s", or "Off".
pub fn refresh_label(secs: u64) -> String {
if secs == 0 {
"Off".into()
} else {
format!("Every {secs} s")
}
}
/// A count with thousands separators: 2815 becomes "2,815".
pub fn count(n: u64) -> String {
let digits = n.to_string();
let first = (digits.len() - 1) % 3 + 1;
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
out.push_str(&digits[..first]);
for (index, digit) in digits[first..].chars().enumerate() {
if index % 3 == 0 {
out.push(',');
}
out.push(digit);
}
out
}
/// A ratio as whole percent: 0.456 becomes "46%"; "—" when there is no ratio.
pub fn percent(ratio: Option<f64>) -> String {
ratio.map_or_else(|| "—".into(), |ratio| format!("{:.0}%", ratio * 100.0))
}
/// `part` of `whole` as whole percent; "—" when `whole` is zero.
pub fn share(part: u64, whole: u64) -> String {
percent((whole > 0).then(|| part as f64 / whole as f64))
}
/// Seconds the short way: "0.7 ms", "8.1 s", "3m 05s", "3h 05m", "2d 3h".
pub fn duration(seconds: f64) -> String {
if !seconds.is_finite() {
return "—".into();
}
let seconds = seconds.max(0.0);
if seconds < 1.0 {
return format!("{:.1} ms", seconds * 1000.0);
}
let tenths = (seconds * 10.0).round() as u64;
let (whole, tenth) = (tenths / 10, tenths % 10);
if whole < 60 {
return format!("{whole}.{tenth} s");
}
let (minutes, second) = (whole / 60, whole % 60);
if minutes < 60 {
return format!("{minutes}m {second:02}s");
}
let (hours, minute) = (minutes / 60, minutes % 60);
if hours < 24 {
return format!("{hours}h {minute:02}m");
}
let (days, hour) = (hours / 24, hours % 24);
format!("{days}d {hour}h")
}
/// A multiple in round numbers: 11432.7 becomes "11,000", 7.42 becomes "7.4".
pub fn round_number(n: f64) -> String {
if !n.is_finite() || n <= 0.0 {
return "—".into();
}
if n < 10.0 {
return format!("{n:.1}");
}
let round_to = if n >= 1000.0 {
100.0
} else if n >= 100.0 {
10.0
} else {
1.0
};
count((n / round_to).round() as u64 * round_to as u64)
}
/// A size in bytes the way file managers show it: "10.0 GB".
pub fn bytes(n: u64) -> String {
const K: f64 = 1024.0;
let (value, unit) = match n as f64 {
value if value < K => return format!("{n} B"),
value if value < K * K => (value / K, "KB"),
value if value < K * K * K => (value / (K * K), "MB"),
value if value < K * K * K * K => (value / (K * K * K), "GB"),
value => (value / (K * K * K * K), "TB"),
};
format!("{value:.1} {unit}")
}
/// Seconds to add to a Unix time to get the clock time of this computer.
/// The browser knows its time zone; a native window would need to find it another way.
pub fn local_offset() -> i64 {
#[cfg(target_arch = "wasm32")]
{
// `get_timezone_offset` is minutes to add to local time to get UTC.
-(js_sys::Date::new_0().get_timezone_offset() as i64) * 60
}
#[cfg(not(target_arch = "wasm32"))]
{
0
}
}
/// A moment as month, day and clock time.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Moment {
pub month: u32,
pub day: u32,
pub hour: u32,
pub minute: u32,
}
/// The moment `unix` seconds after 1 January 1970.
pub fn moment(unix: i64) -> Moment {
let days = unix.div_euclid(86_400);
let secs_of_day = unix.rem_euclid(86_400);
// Howard Hinnant's civil-from-days.
let z = days + 719_468;
let day_of_era = z.rem_euclid(146_097);
let year_of_era =
(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let mp = (5 * day_of_year + 2) / 153;
let day = day_of_year - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
Moment {
month: month as u32,
day: day as u32,
hour: (secs_of_day / 3600) as u32,
minute: (secs_of_day % 3600 / 60) as u32,
}
}
impl Moment {
/// "14:05"
pub fn clock(self) -> String {
format!("{:02}:{:02}", self.hour, self.minute)
}
/// "Nov 12"
pub fn date(self) -> String {
const MONTHS: [&str; 12] = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
];
let month = MONTHS[(self.month.clamp(1, 12) - 1) as usize];
format!("{month} {}", self.day)
}
}
/// "Nov 12, 14:05" for a moment given in Unix seconds.
pub fn moment_text(unix: i64) -> String {
let moment = moment(unix);
format!("{}, {}", moment.date(), moment.clock())
}
/// Spacing of the ticks on a time axis that long, in seconds: whole minutes,
/// hours or days, giving about four to eight ticks.
pub fn tick_step(span_secs: f64) -> i64 {
const STEPS: [i64; 14] = [
60, 120, 300, 600, 900, 1800, 3600, 7200, 10_800, 21_600, 43_200, 86_400, 172_800,
604_800,
];
STEPS
.into_iter()
.find(|step| span_secs / *step as f64 <= 7.5)
.unwrap_or(604_800)
}
/// The label for one tick of a time axis: the clock time, or the date for
/// ticks that fall on midnight or are a day or more apart.
pub fn tick_label(unix: i64, step: i64) -> String {
let moment = moment(unix);
if step >= 86_400 || unix.rem_euclid(86_400) == 0 {
moment.date()
} else {
moment.clock()
}
}
/// What is hidden after the "All languages" box changes: ticked shows every
/// language, cleared hides them all.
pub fn hidden_after_all<'a>(ticked: bool, languages: impl Iterator<Item = &'a str>) -> Vec<String> {
if ticked {
Vec::new()
} else {
languages.map(str::to_owned).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_row_scrolled_above_the_window_still_ends_at_its_own_bottom() {
// Rows closed by their lowest panel: the same answer wherever the page is scrolled.
assert_eq!(lowest([260.0, 300.0, 280.0], 0.0), 300.0);
assert_eq!(lowest([-340.0, -300.0, -320.0], 0.0), -300.0);
assert_eq!(lowest([-17250.0, -17210.5], 0.0), -17210.5);
assert_eq!(lowest([], 42.0), 42.0);
}
#[test]
fn counts_have_thousands_separators() {
assert_eq!(count(0), "0");
assert_eq!(count(325), "325");
assert_eq!(count(2815), "2,815");
assert_eq!(count(123_456), "123,456");
assert_eq!(count(1_234_567_890), "1,234,567,890");
}
#[test]
fn durations_are_short_and_round_cleanly() {
assert_eq!(duration(0.0007), "0.7 ms");
assert_eq!(duration(0.0), "0.0 ms");
assert_eq!(duration(8.14), "8.1 s");
assert_eq!(duration(59.96), "1m 00s");
assert_eq!(duration(185.0), "3m 05s");
assert_eq!(duration(11_100.0), "3h 05m");
assert_eq!(duration(183_600.0), "2d 3h");
assert_eq!(duration(f64::NAN), "—");
}
#[test]
fn moments_match_the_calendar() {
assert_eq!(
moment(0),
Moment {
month: 1,
day: 1,
hour: 0,
minute: 0
}
);
// 1,700,000,000 is 14 November 2023, 22:13:20 UTC.
assert_eq!(moment_text(1_700_000_000), "Nov 14, 22:13");
// Day 95 after the epoch is 6 April 1970.
assert_eq!(moment_text(95 * 86_400 + 12 * 3600), "Apr 6, 12:00");
}
#[test]
fn numbers_are_round_and_ticked() {
assert_eq!(round_number(11_432.7), "11,400");
assert_eq!(round_number(7.42), "7.4");
assert_eq!(bytes(10 * 1024 * 1024 * 1024), "10.0 GB");
assert_eq!(tick_step(3660.0), 600);
assert_eq!(tick_step(86_640.0), 21_600);
assert_eq!(tick_label(43_200, 600), "12:00");
assert_eq!(tick_label(86_400, 600), "Jan 2");
}
#[test]
fn shares_add_up_to_one_hundred() {
assert_eq!(shares(&[50, 33, 17]), [50, 33, 17]);
assert_eq!(shares(&[1, 1, 1]), [34, 33, 33]);
assert_eq!(shares(&[7351, 0, 0, 0, 0]), [100, 0, 0, 0, 0]);
assert_eq!(shares(&[0, 0]), [0, 0]);
let parts = [3254, 3256, 829, 14, 13];
assert_eq!(shares(&parts).iter().sum::<u64>(), 100);
}
#[test]
fn all_languages_box_turns_them_back_on() {
let names = ["Rust", "C/C++"];
assert_eq!(hidden_after_all(true, names.into_iter()), Vec::<String>::new());
assert_eq!(hidden_after_all(false, names.into_iter()), vec!["Rust", "C/C++"]);
}
}
+175
View File
@@ -0,0 +1,175 @@
//! The sccache-dash dashboard page. `trunk` compiles this to WebAssembly and
//! the sccache-dash server serves it at http://127.0.0.1:8226.
pub mod disclosure;
pub mod fmt;
// Drawing needs eframe, which is only built for the browser so far; the rest
// (and the tests) build anywhere.
#[cfg(target_arch = "wasm32")]
mod app;
#[cfg(target_arch = "wasm32")]
mod cards;
#[cfg(target_arch = "wasm32")]
mod extras;
#[cfg(target_arch = "wasm32")]
mod net;
#[cfg(target_arch = "wasm32")]
mod overtime;
#[cfg(target_arch = "wasm32")]
mod problems;
#[cfg(target_arch = "wasm32")]
mod raw;
#[cfg(target_arch = "wasm32")]
mod speed;
#[cfg(target_arch = "wasm32")]
mod style;
#[cfg(target_arch = "wasm32")]
mod theme;
#[cfg(target_arch = "wasm32")]
mod where_went;
/// The canvas in `index.html` the page is drawn on.
pub const CANVAS_ID: &str = "the_canvas_id";
/// Open the dashboard page in the browser.
pub fn open() {
#[cfg(target_arch = "wasm32")]
web::open();
#[cfg(not(target_arch = "wasm32"))]
eprintln!(
"sccache-dash-ui is a web page: build it with `trunk build` in crates/ui. \
There is no native window yet."
);
}
#[cfg(target_arch = "wasm32")]
mod web {
use super::{app::Dashboard, CANVAS_ID};
pub fn open() {
use wasm_bindgen::JsCast;
let canvas = web_sys::window()
.and_then(|window| window.document())
.and_then(|document| document.get_element_by_id(CANVAS_ID))
.and_then(|element| element.dyn_into::<web_sys::HtmlCanvasElement>().ok())
.unwrap_or_else(|| panic!("index.html has no canvas named #{CANVAS_ID}"));
wasm_bindgen_futures::spawn_local(async move {
let options = eframe::WebOptions::default();
eframe::WebRunner::new()
.start(canvas, options, Box::new(|cc| Ok(Box::new(Dashboard::new(cc)))))
.await
.unwrap_or_else(|error| panic!("eframe failed to start: {error:?}"));
});
}
}
#[cfg(test)]
mod tests {
use sccache_dash_api::{Range, View};
/// A view with something in every part of the page.
const SAMPLE: &str = r#"{
"range": "24h",
"generated_at": 1764300000,
"server": {
"status": "Running",
"version": "0.18.0",
"client_version": "0.18.0",
"cache_location": "Local disk: \"/home/me/.cache/sccache\"",
"cache_size": 10726353131,
"max_cache_size": 10737418240,
"error": null
},
"totals": {
"requests": 5610, "executed": 5610, "hits": 2815, "misses": 2795,
"not_cacheable": 0, "unsupported_compiler": 0, "not_compile": 0,
"timeouts": 3, "read_errors": 2, "write_errors": 1, "other_errors": 0,
"compile_fails": 12, "forced_recaches": 4, "cache_writes": 2795
},
"previous": {
"requests": 5000, "executed": 5000, "hits": 2000, "misses": 3000,
"not_cacheable": 0, "unsupported_compiler": 0, "not_compile": 0,
"timeouts": 0, "read_errors": 0, "write_errors": 0, "other_errors": 0,
"compile_fails": 9, "forced_recaches": 0, "cache_writes": 3000
},
"timing": { "avg_hit_read_ms": 0.72, "avg_cache_write_ms": 310.0, "avg_compile_ms": 8050.0 },
"time_saved": {
"seconds": 11100.0, "interval_90": [9700.0, 12600.0], "hits_left_out": 7,
"note": "Low on purpose."
},
"build_times": [
{ "language": "Rust", "compiles": 3256, "mean_ms": 7780.0, "median_ms": 7100.0,
"p90_ms": 21200.0,
"bins": [
{ "from_ms": 1000.0, "to_ms": 1778.28, "compiles": 120 },
{ "from_ms": 1778.28, "to_ms": 3162.28, "compiles": 980 }
] },
{ "language": "CUDA", "compiles": 0, "mean_ms": 0.0, "median_ms": 0.0,
"p90_ms": 0.0, "bins": [] }
],
"languages": [
{ "name": "Rust", "hits": 229, "misses": 3256, "errors": 0 },
{ "name": "C/C++", "hits": 2082, "misses": 0, "errors": 0 }
],
"not_cached": [{"reason": "crate-type", "count": 621, "name": "Programs and libraries that get linked", "meaning": "m", "action": "a", "fixable": false}, {"reason": "incremental", "count": 105, "name": "n", "meaning": "m", "action": "a", "fixable": true}],
"buckets": [
{ "start": 1764290000, "hits": 10, "misses": 5, "other": 1, "errors": 0, "saved_seconds": 60.0,
"languages": [["Rust", 10, 5]], "reset": false, "gap": false },
{ "start": 1764290600, "hits": 0, "misses": 0, "other": 0, "errors": 0, "saved_seconds": 0.0,
"languages": [], "reset": false, "gap": true },
{ "start": 1764291200, "hits": 4, "misses": 4, "other": 0, "errors": 0, "saved_seconds": 30.0,
"languages": [["C/C++", 4, 4]], "reset": true, "gap": false }
],
"problems": [
{ "severity": "Warning", "title": "Rust hit rate 8%", "detail": "Most Rust compiles miss." }
],
"extras": [ { "title": "Multi-level cache", "rows": [["Levels", "2"]] } ],
"raw": { "stats": { "compile_requests": 5610 }, "version": "0.18.0" },
"summary_markdown": "**Cache:** 50%"
}"#;
#[test]
fn a_view_deserialises() {
let view: View = serde_json::from_str(SAMPLE).expect("the sample is a View");
assert_eq!(view.range, Some(Range::Day));
assert_eq!(view.totals.hit_rate(), Some(2815.0 / 5610.0));
assert_eq!(view.server.version.as_deref(), Some("0.18.0"));
assert_eq!(view.time_saved.interval_90, Some((9700.0, 12600.0)));
assert_eq!(view.build_times[0].bins[1].compiles, 980);
assert_eq!(view.build_times[1].compiles, 0);
assert_eq!((view.not_cached[0].reason.as_str(), view.not_cached[0].count), ("crate-type", 621));
assert!(view.not_cached[1].fixable);
assert_eq!(view.buckets[1].gap, true);
assert_eq!(view.extras[0].rows[0].1, "2");
}
#[test]
fn an_empty_view_deserialises() {
// Every field is present, as the server always sends them; several are empty.
let view: View = serde_json::from_str(
r#"{"range": null, "generated_at": 0, "server": {"status": "NotRunning"},
"totals": {
"requests": 0, "executed": 0, "hits": 0, "misses": 0, "not_cacheable": 0,
"unsupported_compiler": 0, "not_compile": 0, "timeouts": 0, "read_errors": 0,
"write_errors": 0, "other_errors": 0, "compile_fails": 0, "forced_recaches": 0,
"cache_writes": 0
},
"previous": null,
"timing": {
"avg_hit_read_ms": null, "avg_cache_write_ms": null, "avg_compile_ms": null
},
"time_saved": {"seconds": 0.0, "hits_left_out": 0, "note": ""},
"languages": [], "not_cached": [], "buckets": [], "problems": [], "extras": [],
"raw": null, "summary_markdown": ""}"#,
)
.expect("an empty view is still a View");
assert_eq!(view.totals.hit_rate(), None);
assert_eq!(view.time_saved.interval_90, None);
assert!(view.build_times.is_empty());
assert!(view.raw.is_null());
}
}
+5
View File
@@ -0,0 +1,5 @@
//! Entry point of the WebAssembly module; the page itself lives in the library.
fn main() {
sccache_dash_ui::open();
}
+110
View File
@@ -0,0 +1,110 @@
//! Talking to the server. One request is in flight at a time.
use std::sync::{Arc, Mutex};
use eframe::egui;
use sccache_dash_api::{Range, View};
/// A request sent to the server; its answer is picked up on a later frame.
pub struct Answer {
slot: Arc<Mutex<Option<Result<ehttp::Response, String>>>>,
}
impl Answer {
pub fn send(request: ehttp::Request, ctx: &egui::Context) -> Self {
let slot = Arc::new(Mutex::new(None));
let sink = Arc::clone(&slot);
let ctx = ctx.clone();
ehttp::fetch(request, move |result| {
if let Ok(mut sink) = sink.lock() {
*sink = Some(result);
}
ctx.request_repaint();
});
Self { slot }
}
/// The answer, once it has arrived.
pub fn take(&self) -> Option<Result<ehttp::Response, String>> {
self.slot.lock().ok().and_then(|mut slot| slot.take())
}
}
/// Ask for the view of a range.
pub fn view(range: Range) -> ehttp::Request {
ehttp::Request::get(format!("/api/view?range={}", range.code()))
}
/// Ask the server to zero sccache's counters.
pub fn zero() -> ehttp::Request {
ehttp::Request::post("/api/zero", Vec::new())
}
/// The view inside a server answer.
pub fn view_from(answer: Result<ehttp::Response, String>) -> Result<View, String> {
let response = answer?;
if !response.ok {
return Err(format!(
"the server answered {} {}{}",
response.status,
response.status_text,
body_hint(response.text())
));
}
serde_json::from_slice(&response.bytes)
.map_err(|error| format!("the server's answer could not be read ({error})"))
}
/// Whether a request that changes something was accepted.
pub fn accepted(answer: Result<ehttp::Response, String>) -> Result<(), String> {
let response = answer?;
if response.ok {
Ok(())
} else {
Err(format!(
"the server answered {} {}{}",
response.status,
response.status_text,
body_hint(response.text())
))
}
}
fn body_hint(body: Option<&str>) -> String {
let body = body.map_or("", |body| body.trim());
if body.is_empty() {
String::new()
} else {
let shown: String = body.chars().take(200).collect();
format!(": {shown}")
}
}
/// Have the browser download a file the server serves.
pub fn download(url: &str) -> Result<(), String> {
#[cfg(target_arch = "wasm32")]
{
use wasm_bindgen::JsCast;
let document = web_sys::window()
.and_then(|window| window.document())
.ok_or("the browser has no document")?;
let element = document
.create_element("a")
.map_err(|error| error.as_string().unwrap_or_default())?;
let link = element
.dyn_into::<web_sys::HtmlAnchorElement>()
.map_err(|_| "the browser could not make a download link".to_owned())?;
link.set_href(url);
link.set_attribute("download", "")
.map_err(|error| error.as_string().unwrap_or_default())?;
link.click();
Ok(())
}
#[cfg(not(target_arch = "wasm32"))]
{
let _ = url;
Err("saving files is only wired up for the browser".into())
}
}
+397
View File
@@ -0,0 +1,397 @@
//! Over time: hit rate and compile volume per bucket, with a language filter.
//! Both charts always show the whole selected range; time nothing was recorded
//! in is tinted and labelled once.
use eframe::egui::{self, Stroke, Ui};
use egui_plot::{
Bar, BarChart, CoordinatesFormatter, Corner, GridInput, GridMark, Line, LineStyle, Plot,
PlotBounds, PlotPoint, PlotPoints, PlotResponse, PlotUi, Span, VLine,
};
use sccache_dash_api::{Bucket, Range, View};
use crate::fmt;
use crate::style;
use crate::theme;
/// Hits out of the cacheable compiles; `None` when there were none.
pub fn hit_rate(hits: u64, misses: u64) -> Option<f64> {
(hits + misses > 0).then(|| hits as f64 / (hits + misses) as f64)
}
fn axes_of(view: &View, dark: bool) -> Axes {
let step = bucket_step(&view.buckets, view.range);
Axes {
window: range_window(view, step),
step,
tz: fmt::local_offset() as f64,
dark,
}
}
/// The body of the "Hit rate over time" panel.
pub fn hit_rate_panel(ui: &mut Ui, view: &View, hidden: &[String], chart_height: f32) {
let axes = axes_of(view, theme::ui(ui).dark);
hit_rate_chart(ui, view, hidden, axes, chart_height);
}
/// The body of the "Compiles over time" panel.
pub fn volume_panel(ui: &mut Ui, view: &View, hidden: &[String], chart_height: f32) {
let axes = axes_of(view, theme::ui(ui).dark);
volume_chart(ui, view, hidden, axes, chart_height);
}
/// The title of one part of a panel, in the style of a panel title.
pub fn part_title(ui: &mut Ui, text: &str) {
ui.add(egui::Label::new(theme::title(ui, text)).truncate());
}
/// Checkboxes that narrow both charts to some languages.
pub fn filter(ui: &mut Ui, view: &View, hidden: &mut Vec<String>) {
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing.x = theme::space::PANEL_GAP;
let mut all = hidden.is_empty();
if ui.checkbox(&mut all, "All languages").changed() {
*hidden = fmt::hidden_after_all(all, view.languages.iter().map(|l| l.name.as_str()));
}
for language in &view.languages {
let mut ticked = !hidden.iter().any(|name| name == &language.name);
if ui.checkbox(&mut ticked, language.name.as_str()).changed() {
if ticked {
hidden.retain(|name| name != &language.name);
} else {
hidden.push(language.name.clone());
}
}
}
});
if !hidden.is_empty() {
ui.add(
egui::Label::new(
theme::small(
ui,
"Only the chosen languages are counted. The other outcomes can't be split by \
language, so they're left out.",
),
),
);
}
}
/// How many seconds each bucket covers.
fn bucket_step(buckets: &[Bucket], range: Option<Range>) -> f64 {
let length = match range {
Some(Range::Hour) => 3_600.0,
Some(Range::Day) => 86_400.0,
Some(Range::Week) => 604_800.0,
Some(Range::Month) => 2_592_000.0,
_ => 7_200.0,
};
match buckets.len() {
0 | 1 => length / 120.0,
count => (buckets[count - 1].start - buckets[0].start) as f64 / (count - 1) as f64,
}
}
/// The whole selected range as Unix seconds (start, end): a fixed-length range
/// runs back from now by its length, whatever the buckets cover; "since reset"
/// runs from the first bucket to the last one's end.
fn range_window(view: &View, step: f64) -> (f64, f64) {
let now = view.generated_at as f64;
let (first, last) = match (view.buckets.first(), view.buckets.last()) {
(Some(first), Some(last)) => (first.start as f64, last.start as f64 + step),
_ => (now - step, now),
};
match view.range {
Some(Range::Hour) => (now - 3_600.0, now),
Some(Range::Day) => (now - 86_400.0, now),
Some(Range::Week) => (now - 604_800.0, now),
Some(Range::Month) => (now - 2_592_000.0, now),
_ => (first, last.max(first + step)),
}
}
/// The stretches of the window no recorded bucket covers.
fn unrecorded(buckets: &[Bucket], window: (f64, f64), step: f64) -> Vec<(f64, f64)> {
let mut stretches = Vec::new();
let mut cursor = window.0;
for bucket in buckets.iter().filter(|bucket| !bucket.gap) {
let (from, to) = (bucket.start as f64, bucket.start as f64 + step);
if from > cursor {
stretches.push((cursor, from));
}
cursor = cursor.max(to);
}
if cursor < window.1 {
stretches.push((cursor, window.1));
}
stretches
}
/// What both charts share.
#[derive(Clone, Copy)]
struct Axes {
/// Start and end of the range in Unix seconds.
window: (f64, f64),
/// Seconds per bucket.
step: f64,
/// Seconds to add to a Unix time to get local clock time.
tz: f64,
dark: bool,
}
/// A chart with a time axis over the whole range: clock times as ticks and a
/// readout of where the pointer is. It can't be zoomed or dragged, so the wheel
/// and a finger keep scrolling the page; that also means it can fit its data
/// afresh every frame, so new buckets are never cut off. A little air either
/// side keeps the first and last time label inside the plot.
fn time_plot<'a>(
name: &'static str,
axes: Axes,
height: f32,
readout: impl Fn(&PlotPoint) -> String + 'a,
) -> Plot<'a> {
let (first, last) = (axes.window.0 + axes.tz, axes.window.1 + axes.tz);
let span = last - first;
let air = span * theme::drawing::CHART_SIDE_AIR;
let tick = fmt::tick_step(span);
let label_font = egui::FontId::proportional(theme::px::SMALL);
let label_color = theme::of(axes.dark).muted;
let (from, to) = (first, last);
Plot::new(name)
.height(height)
.show_background(false)
.grid_color(theme::of(axes.dark).grid)
.allow_scroll(false)
.allow_drag(false)
.allow_zoom(false)
.allow_boxed_zoom(false)
.custom_x_axes(vec![egui_plot::AxisHints::new_x()
.tick_label_font(label_font.clone())
.tick_label_color(label_color)])
.custom_y_axes(vec![egui_plot::AxisHints::new_y()
.tick_label_font(label_font)
.tick_label_color(label_color)])
// The range and a little air either side, so the edge labels are not cut off.
.default_x_bounds(first - air, last + air)
.x_grid_spacer(move |input: GridInput| {
ticks(input.bounds.0, input.bounds.1, tick)
.into_iter()
.filter(|mark| mark.value >= from && mark.value <= to)
.collect()
})
.x_axis_formatter(move |mark: GridMark, _range| {
fmt::tick_label(mark.value.round() as i64, tick)
})
.coordinates_formatter(
Corner::LeftTop,
CoordinatesFormatter::new(move |point: &PlotPoint, _bounds: &PlotBounds| readout(point)),
)
.reset()
}
fn ticks(from: f64, to: f64, tick: i64) -> Vec<GridMark> {
let tick = tick.max(1);
let first = from.ceil() as i64;
let mut value = first - first.rem_euclid(tick);
let mut marks = Vec::new();
while value as f64 <= to {
marks.push(GridMark {
value: value as f64,
step_size: tick as f64,
});
value += tick;
}
marks
}
/// Resets as dashed lines, and everything unrecorded as one tinted band per stretch.
fn marks(plot: &mut PlotUi<'_>, buckets: &[Bucket], axes: Axes) {
let p = theme::of(axes.dark);
for bucket in buckets {
if bucket.reset {
plot.vline(
VLine::new("Reset", bucket.start as f64 + axes.tz)
.stroke(Stroke::new(1.5, p.warn))
.style(LineStyle::Dashed { length: 12.0 }),
);
}
}
for (from, to) in unrecorded(buckets, axes.window, axes.step) {
plot.span(
Span::new("Not recorded", (from + axes.tz)..=(to + axes.tz))
.fill(p.unrecorded)
.border_width(0.0),
);
}
}
/// Whether there is anything to mark: a reset, or time nothing was recorded in.
fn marked(buckets: &[Bucket], axes: Axes) -> (bool, bool) {
let any_reset = buckets.iter().any(|bucket| bucket.reset);
let any_gap = !unrecorded(buckets, axes.window, axes.step).is_empty();
(any_reset, any_gap)
}
fn overlay(ui: &mut Ui, chart: &PlotResponse<()>, text: &str) {
ui.painter().text(
chart.response.rect.center(),
egui::Align2::CENTER_CENTER,
text,
egui::FontId::proportional(theme::px::SMALL),
theme::ui(ui).muted,
);
}
/// Hits and misses of a bucket, for the languages that are ticked.
fn split(bucket: &Bucket, hidden: &[String]) -> (u64, u64) {
if hidden.is_empty() {
(bucket.hits, bucket.misses)
} else {
bucket
.languages
.iter()
.filter(|(name, _, _)| !hidden.contains(name))
.fold((0, 0), |(hits, misses), (_, hits_here, misses_here)| {
(hits + hits_here, misses + misses_here)
})
}
}
fn hit_rate_chart(ui: &mut Ui, view: &View, hidden: &[String], axes: Axes, height: f32) {
let p = theme::ui(ui);
// One line per stretch of buckets that have a hit rate.
let mut runs: Vec<Vec<PlotPoint>> = Vec::new();
let mut run: Vec<PlotPoint> = Vec::new();
for bucket in view.buckets.iter().filter(|bucket| !bucket.gap) {
let (hits, misses) = split(bucket, hidden);
match hit_rate(hits, misses) {
Some(rate) => run.push(PlotPoint::new(
bucket.start as f64 + axes.tz,
rate * 100.0,
)),
None if !run.is_empty() => runs.push(std::mem::take(&mut run)),
None => {}
}
}
if !run.is_empty() {
runs.push(run);
}
let plot = time_plot(
"hit-rate-chart",
axes,
height,
|point| format!("{} · {:.0}%", fmt::moment_text(point.x.round() as i64), point.y),
)
.default_y_bounds(0.0, 100.0)
// A mark every quarter, so the axis reads 0%, 25%, 50%, 75%, 100%.
.y_grid_spacer(|_: GridInput| {
(0..=4)
.map(|quarter| GridMark {
value: quarter as f64 * 25.0,
step_size: 25.0,
})
.collect()
})
.y_axis_formatter(|mark: GridMark, _| format!("{:.0}%", mark.value));
let chart = plot.show(ui, |plot| {
marks(plot, &view.buckets, axes);
for points in &runs {
plot.line(
Line::new("Hit rate", PlotPoints::Owned(points.clone()))
.color(p.from_cache)
.width(2.0),
);
}
});
if runs.is_empty() {
overlay(ui, &chart, "No cacheable compiles in this range");
}
let (any_reset, any_gap) = marked(&view.buckets, axes);
let mut entries = vec![(style::Mark::Line(p.from_cache), "Hit rate".to_owned())];
if any_reset {
entries.push((style::Mark::Dashed(p.warn), "Reset".to_owned()));
}
if any_gap {
entries.push((style::Mark::Band, "Not recorded".to_owned()));
}
style::legend(ui, entries);
}
fn volume_chart(ui: &mut Ui, view: &View, hidden: &[String], axes: Axes, height: f32) {
let p = theme::ui(ui);
// The tallest stack of one bucket, with a little air above it.
let top = view
.buckets
.iter()
.filter(|bucket| !bucket.gap)
.fold(4.0_f64, |top, bucket| {
let (hits, misses) = split(bucket, hidden);
let other = if hidden.is_empty() { bucket.other } else { 0 };
top.max((hits + misses + other) as f64 * 1.1)
});
let plot = time_plot(
"volume-chart",
axes,
height,
|point| fmt::moment_text(point.x.round() as i64),
)
.default_y_bounds(0.0, top)
.y_axis_formatter(|mark: GridMark, _| fmt::count(mark.value.max(0.0).round() as u64));
let width = axes.step * 0.8;
let (mut from_cache, mut built, mut other) = (vec![], vec![], vec![]);
let mut any = false;
for bucket in view.buckets.iter().filter(|bucket| !bucket.gap) {
let x = bucket.start as f64 + axes.tz;
let (hits, misses) = split(bucket, hidden);
for (bars, count) in [
(&mut from_cache, hits),
(&mut built, misses),
(&mut other, bucket.other),
] {
if count > 0 {
bars.push(Bar::new(x, count as f64));
any = true;
}
}
}
let chart = plot.show(ui, |plot| {
marks(plot, &view.buckets, axes);
let from_cache = BarChart::new("From cache", from_cache)
.width(width)
.color(p.from_cache);
let built = BarChart::new("Built", built)
.width(width)
.color(p.built);
let other = BarChart::new("Not cacheable and other", other)
.width(width)
.color(p.not_cacheable);
let built = built.stack_on(&[&from_cache]);
let other = other.stack_on(&[&built]);
plot.bar_chart(from_cache);
plot.bar_chart(built);
if hidden.is_empty() {
plot.bar_chart(other);
}
});
if !any {
overlay(ui, &chart, "Nothing recorded in this range");
}
let (any_reset, any_gap) = marked(&view.buckets, axes);
let mut entries = vec![
(style::Mark::Fill(p.from_cache), "From cache".to_owned()),
(style::Mark::Fill(p.built), "Built".to_owned()),
];
if hidden.is_empty() {
entries.push((style::Mark::Fill(p.not_cacheable), "Not cacheable and other".to_owned()));
}
if any_reset {
entries.push((style::Mark::Dashed(p.warn), "Reset".to_owned()));
}
if any_gap {
entries.push((style::Mark::Band, "Not recorded".to_owned()));
}
style::legend(ui, entries);
}
+77
View File
@@ -0,0 +1,77 @@
//! Problems: what is wrong, most serious first, as the list under the hero's problem
//! count. Each problem is a line (a square for how serious, its title, a chevron); clicking
//! it shows the full explanation under it, as the reasons list does. The list scrolls inside
//! a fixed height, so a longer list or an open explanation never moves the page.
use eframe::egui::{self, Sense, Ui};
use sccache_dash_api::{Severity, View};
use crate::theme;
use crate::where_went::chevron;
const ROW: f32 = 22.0;
const GAP: f32 = 8.0;
const CHEVRON: f32 = 8.0;
fn open_id(title: &str) -> egui::Id {
egui::Id::new(("problem-open", title))
}
/// The problems of `view` in a list `height` tall.
pub fn hero_list(ui: &mut Ui, view: &View, height: f32) {
let p = theme::ui(ui);
if view.problems.is_empty() {
ui.add(egui::Label::new(theme::small(ui, "Nothing needs attention.")).truncate());
return;
}
egui::ScrollArea::vertical()
.id_salt("hero-problems")
.max_height(height)
.auto_shrink([false, false])
.show(ui, |ui| {
ui.spacing_mut().item_spacing.y = 0.0;
let width = ui.available_width();
let indent = theme::drawing::SEVERITY_DOT + GAP;
for problem in &view.problems {
let id = open_id(&problem.title);
let open = ui.ctx().data(|data| data.get_temp::<bool>(id)).unwrap_or(false);
let (row, response) = ui.allocate_exact_size(egui::vec2(width, ROW), Sense::click());
let response = response.on_hover_cursor(egui::CursorIcon::PointingHand);
response.widget_info(|| {
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, problem.title.as_str())
});
if response.clicked() {
ui.ctx().data_mut(|data| data.insert_temp(id, !open));
ui.ctx().request_repaint();
}
if response.hovered() {
ui.painter().rect_filled(row, theme::space::CONTROL_RADIUS, p.hover);
}
let color = match problem.severity {
Severity::Error => p.bad,
Severity::Warning => p.warn,
};
let side = theme::drawing::SEVERITY_DOT;
ui.painter().rect_filled(
egui::Rect::from_center_size(egui::pos2(row.left() + side / 2.0, row.center().y), egui::vec2(side, side)),
0.0,
color,
);
let chevron_x = row.right() - CHEVRON;
chevron(ui.painter(), egui::pos2(chevron_x + CHEVRON / 2.0, row.center().y), open, p.muted);
let title = crate::style::galley(ui, theme::body(problem.title.clone()), false, f32::INFINITY);
let room = (chevron_x - GAP - row.left() - indent).max(10.0);
let place = egui::Rect::from_min_size(egui::pos2(row.left() + indent, row.top()), egui::vec2(room, ROW));
ui.painter().with_clip_rect(place).galley(
egui::pos2(place.left(), row.center().y - title.size().y / 2.0),
title,
p.text,
);
if open {
let detail = crate::style::galley(ui, theme::small(ui, problem.detail.clone()), true, width - indent);
let (place, _) = ui.allocate_exact_size(egui::vec2(width, detail.size().y + 6.0), Sense::hover());
ui.painter().galley(egui::pos2(place.left() + indent, place.top()), detail, p.muted);
}
}
});
}
+157
View File
@@ -0,0 +1,157 @@
//! Raw counters: the sccache stats exactly as the server read them, as compact
//! key/value lines that flow in columns. The panel opens and closes; it starts
//! closed, as one line.
use std::cell::Cell;
use eframe::egui::{self, Pos2, Rect, Sense, Ui};
use sccache_dash_api::View;
use crate::style;
use crate::theme;
/// Every leaf of the JSON as its dotted path and its value as text.
fn leaves(value: &serde_json::Value, path: String, out: &mut Vec<(String, String)>) {
match value {
serde_json::Value::Object(fields) => {
for (name, value) in fields {
let path = if path.is_empty() { name.clone() } else { format!("{path}.{name}") };
leaves(value, path, out);
}
}
serde_json::Value::Array(items) => {
for (index, value) in items.iter().enumerate() {
leaves(value, format!("{path}[{index}]"), out);
}
}
leaf => out.push((
path,
match leaf {
serde_json::Value::String(text) => text.clone(),
serde_json::Value::Null => "null".to_owned(),
number => number.to_string(),
},
)),
}
}
/// How many columns of key/value lines fit in a panel's `inner` width.
fn columns(inner: f32) -> usize {
let gap = theme::space::PANEL_GAP + 4.0;
(((inner + gap) / (theme::layout::RAW_LINE_WIDTH + gap)) as usize).clamp(1, 3)
}
/// How tall the panel is when it is `width` wide: its title and, when open,
/// its lines.
pub fn height(view: &View, width: f32, open: bool) -> f32 {
let title = theme::space::ROW + theme::space::UNDER_TITLE + 2.0 * theme::space::PANEL_PAD_Y;
if !open {
return title - theme::space::UNDER_TITLE + theme::space::LINE;
}
let mut lines = 0;
if !view.raw.is_null() {
let mut out = Vec::new();
leaves(&view.raw, String::new(), &mut out);
lines = out.len();
}
let inner = width - 2.0 * theme::space::PANEL_PADDING;
title + lines.div_ceil(columns(inner)) as f32 * theme::space::ROW
}
/// The panel at `rect`; its title opens and closes it. Returns the rect it took.
pub fn section(ui: &mut Ui, view: &View, rect: Rect) -> Rect {
let id = egui::Id::new("raw-counters-open");
let open = Cell::new(ui.ctx().data_mut(|data| data.get_temp::<bool>(id)).unwrap_or(false));
let (_, taken) = style::panel_titled(
ui,
rect,
|ui| {
let mut now = open.get();
style::toggling_title(ui, "Raw counters", &mut now);
open.set(now);
},
|ui| {
let open = open.get();
ui.ctx().data_mut(|data| data.insert_temp(id, open));
if !open {
return;
}
match &view.raw {
serde_json::Value::Null => {
ui.label(theme::body("sccache's raw counters could not be read."));
}
value => {
let mut lines = Vec::new();
leaves(value, String::new(), &mut lines);
flow(ui, &lines);
}
}
},
);
taken
}
/// Key/value lines in as many columns of the raw line width as fit, filled
/// left to right and then down: each line in its own cell, the key in small
/// print and the value in mono right after it.
fn flow(ui: &mut Ui, lines: &[(String, String)]) {
let p = theme::ui(ui);
let width = ui.available_rect_before_wrap().width();
let gap = theme::space::PANEL_GAP + 4.0;
let columns = columns(width);
let cell = (width - gap * (columns - 1) as f32) / columns as f32;
let font = egui::FontId::proportional(theme::px::SMALL);
let mono = theme::number_font(theme::px::SMALL);
for line in lines.chunks(columns) {
// One exact row of cells: a row is laid out, never wrapped, so every column is used.
ui.allocate_ui_with_layout(
egui::vec2(width, theme::space::ROW),
egui::Layout::left_to_right(egui::Align::Center),
|ui| {
ui.spacing_mut().item_spacing.x = gap;
for (key, value) in line {
let (rect, response) =
ui.allocate_exact_size(egui::vec2(cell, theme::space::ROW), Sense::hover());
let painter = ui.painter();
let clip = rect.intersect(ui.clip_rect());
let value_galley = painter.layout_no_wrap(value.clone(), mono.clone(), p.text);
let value_width = value_galley.size().x;
// The value follows its key by the key/value gap, not pushed to the cell's edge;
// where the two do not fit, the key ends in "…" and all of it shows on hover.
let key_room = (rect.width() - theme::space::KEY_VALUE_GAP - value_width).max(0.0);
let key_galley = painter.layout_no_wrap(key.clone(), font.clone(), p.muted);
let key_width = key_galley.size().x;
let cut = key_width > key_room;
let key_galley = if cut {
let mut chars = key.chars().count();
loop {
chars -= 1;
let shorter: String = key.chars().take(chars).collect::<String>() + "…";
let galley = painter.layout_no_wrap(shorter, font.clone(), p.muted);
if galley.size().x <= key_room || chars <= 1 {
break galley;
}
}
} else {
key_galley
};
let key_width = key_galley.size().x;
painter.with_clip_rect(clip).galley(
Pos2::new(rect.left(), rect.center().y - key_galley.size().y / 2.0),
key_galley,
p.muted,
);
let value_left = rect.left() + key_width + theme::space::KEY_VALUE_GAP;
painter.with_clip_rect(clip).galley(
Pos2::new(value_left, rect.center().y - value_galley.size().y / 2.0),
value_galley,
p.text,
);
if cut || value_left + value_width > rect.right() {
response.on_hover_text(format!("{key} {value}"));
}
}
},
);
}
}
+210
View File
@@ -0,0 +1,210 @@
//! Speed: how long a cache fetch, a cache write and a build take on average,
//! and how build times spread for each language.
use eframe::egui::{self, Pos2, Rect, Sense, Ui};
use sccache_dash_api::{BuildTimes, View};
use crate::fmt;
use crate::style;
use crate::theme;
/// The slowest build time the axis reaches, as log10 of milliseconds (1,000 s).
const AXIS_TOP: f64 = 6.0;
/// The width of the label and of the value beside each speed bar.
const LABEL_WIDTH: f32 = 128.0;
const VALUE_WIDTH: f32 = 60.0;
pub fn section(ui: &mut Ui, view: &View) {
let p = theme::ui(ui);
let timing = view.timing;
let rows = [
("Cache fetch (a hit)", timing.avg_hit_read_ms, p.from_cache),
("Cache write", timing.avg_cache_write_ms, p.muted),
("Compile one crate", timing.avg_compile_ms, p.built),
];
for (label, ms, color) in rows {
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = theme::space::ITEM;
let (label_rect, _) =
ui.allocate_exact_size(egui::vec2(LABEL_WIDTH, theme::space::ROW), Sense::hover());
let label = style::galley(ui, theme::body(label), false, f32::INFINITY);
ui.painter().with_clip_rect(label_rect).galley(
Pos2::new(label_rect.left(), label_rect.center().y - label.size().y / 2.0),
label,
p.text,
);
let text = ms.map_or("—".into(), |ms| fmt::duration(ms / 1000.0));
let value = style::galley(ui, theme::number(text), false, f32::INFINITY);
let value_rect = ui
.allocate_exact_size(egui::vec2(VALUE_WIDTH, theme::space::ROW), Sense::hover())
.0;
ui.painter().with_clip_rect(value_rect).galley(
Pos2::new(value_rect.right() - value.size().x, value_rect.center().y - value.size().y / 2.0),
value,
p.text,
);
let bar_rect = ui
.allocate_exact_size(
egui::vec2(ui.available_rect_before_wrap().width(), theme::space::ROW),
Sense::hover(),
)
.0;
let bar = Rect::from_center_size(
bar_rect.center(),
egui::vec2(bar_rect.width(), theme::drawing::SPEED_BAR),
);
style::fill_bar(ui, bar, ms.map_or(0.0, style::log_fraction), color);
});
}
let hit = timing.avg_hit_read_ms;
let write = timing.avg_cache_write_ms;
let build = timing.avg_compile_ms;
let sentence = if let Some(times) = faster(build, hit) {
format!("A cache hit is about {times}x faster than compiling the crate.")
} else if let Some(times) = faster(build, write) {
format!("Writing to the cache is about {times}x faster than compiling the crate.")
} else {
"There are no timings to compare in this range.".to_owned()
};
ui.add_space(theme::space::ITEM);
ui.add(egui::Label::new(theme::strong(sentence).color(p.hero)).wrap());
ui.add(
egui::Label::new(
theme::small(
ui,
"The bars use a log scale, so a fraction of a millisecond and several seconds are \
both visible.",
),
),
);
build_times(ui, view);
}
/// `faster` is about how many times shorter than `slower`, when both are known and positive.
fn faster(slower: Option<f64>, faster: Option<f64>) -> Option<String> {
let (slower, faster) = (slower?, faster?);
(slower > 0.0 && faster > 0.0).then(|| fmt::round_number(slower / faster))
}
/// "How long one crate takes to compile": one histogram per language, all on the
/// same log scale of build time, with the mean, median and p90 marked.
fn build_times(ui: &mut Ui, view: &View) {
let p = theme::ui(ui);
let languages: Vec<&BuildTimes> = view
.build_times
.iter()
.filter(|times| times.compiles > 0 && !times.bins.is_empty())
.collect();
if languages.is_empty() {
return;
}
ui.add_space(theme::space::BETWEEN_PARTS);
crate::overtime::part_title(ui, "How long one crate takes to compile");
// One shared axis, from a quarter step before the fastest bin to a quarter step after the slowest.
let (mut low, mut high) = (f64::MAX, 0.0_f64);
for times in &languages {
for bin in &times.bins {
low = low.min(bin.from_ms);
high = high.max(bin.to_ms);
}
}
let low = (low.max(1.0).log10() - 0.25).max(0.0);
let high = (high.log10() + 0.25).min(AXIS_TOP);
for times in languages {
ui.add_space(theme::space::ITEM);
ui.horizontal(|ui| {
ui.spacing_mut().item_spacing.x = theme::space::ITEM;
ui.add(egui::Label::new(theme::strong(times.language.clone())).truncate());
ui.add(egui::Label::new(theme::small(ui, format!("{} compiles", fmt::count(times.compiles)))).truncate());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.spacing_mut().item_spacing.x = theme::space::ITEM;
for (name, value, color) in [
("p90", times.p90_ms, p.p90),
("median", times.median_ms, p.median),
("mean", times.mean_ms, p.mean),
] {
ui.label(theme::small(ui, format!("{name} {}", ms(value))).color(color));
}
});
});
histogram(ui, times, low, high, p);
axis(ui, low, high);
}
ui.add(
egui::Label::new(
theme::small(
ui,
"Each point is the average of the builds that finished within one 10-second reading.",
),
),
);
}
fn ms(value: f64) -> String {
fmt::duration(value / 1000.0)
}
/// The bins as bars, build time along the bottom on a log scale, with a line
/// for the mean, median and p90.
fn histogram(ui: &mut Ui, times: &BuildTimes, low: f64, high: f64, p: &theme::Palette) {
let width = ui.available_rect_before_wrap().width();
let (rect, response) = ui.allocate_exact_size(
egui::vec2(width, theme::drawing::BUILD_HISTOGRAM),
Sense::hover(),
);
let painter = ui.painter();
painter.hline(rect.x_range(), rect.bottom() - 0.5, egui::Stroke::new(1.0, p.grid));
let at = |value: f64| {
let position = ((value.max(1.0).log10() - low) / (high - low)).clamp(0.0, 1.0);
rect.left() + rect.width() * position as f32
};
let top = times.bins.iter().map(|bin| bin.compiles).max().unwrap_or(0);
for bin in &times.bins {
if bin.compiles == 0 {
continue;
}
let height = theme::drawing::BUILD_HISTOGRAM * bin.compiles as f32 / top.max(1) as f32;
let bar = Rect::from_min_max(
Pos2::new(at(bin.from_ms), rect.bottom() - height),
Pos2::new((at(bin.to_ms) - 1.0).max(at(bin.from_ms) + 1.0), rect.bottom()),
);
painter.rect_filled(bar, 1.0, p.built);
}
for (value, color) in [times.mean_ms, times.median_ms, times.p90_ms].into_iter().zip([p.mean, p.median, p.p90]) {
let x = at(value);
painter.rect_filled(
Rect::from_min_max(Pos2::new(x, rect.top()), Pos2::new(x + 2.0, rect.bottom())),
0.0,
color,
);
}
response.on_hover_text(format!(
"{} builds: mean {}, median {}, p90 {}",
fmt::count(times.compiles),
ms(times.mean_ms),
ms(times.median_ms),
ms(times.p90_ms)
));
}
/// The times along the bottom of a histogram: one mark every tenfold step.
fn axis(ui: &mut Ui, low: f64, high: f64) {
let p = theme::ui(ui);
let width = ui.available_rect_before_wrap().width();
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, theme::drawing::BUILD_AXIS), Sense::hover());
let font = egui::FontId::proportional(theme::px::SMALL);
for step in 0..=AXIS_TOP as i64 {
let value = step as f64;
if value < low || value > high {
continue;
}
let x = rect.left() + rect.width() * ((value - low) / (high - low)) as f32;
let text = ms(10.0_f64.powf(value));
let galley = ui.painter().layout_no_wrap(text, font.clone(), p.muted);
let x = x.clamp(rect.left(), rect.right() - galley.size().x);
ui.painter().galley(Pos2::new(x, rect.center().y - galley.size().y / 2.0), galley, p.muted);
}
}
+630
View File
@@ -0,0 +1,630 @@
//! Drawings shared by the panels: the grid, panels, cards, tables, bars and
//! chart keys. Every colour and size comes from [`crate::theme`].
use std::sync::Arc;
use eframe::egui::{self, Align, Align2, Color32, Galley, Layout, Pos2, Rect, RichText, Sense, Shape, Stroke, StrokeKind, Ui};
use egui::TextWrapMode;
use crate::theme::{self, px, space};
/// The palette of the theme being drawn.
pub fn p(ui: &Ui) -> &'static theme::Palette {
theme::ui(ui)
}
/// The width of `text` in `font`.
pub fn text_width(ui: &Ui, text: &str, font: egui::FontId) -> f32 {
ui.painter()
.layout_no_wrap(text.to_owned(), font, theme::ui(ui).text)
.size()
.x
}
/// Lay `text` out: on one line, or wrapped at `width` when `wrap` is set.
pub fn galley(ui: &Ui, text: RichText, wrap: bool, width: f32) -> Arc<Galley> {
egui::WidgetText::from(text).into_galley(
ui,
Some(if wrap { TextWrapMode::Wrap } else { TextWrapMode::Extend }),
width,
egui::FontSelection::Default,
)
}
/// A colour made see-through.
pub fn tint(color: Color32, share: f32) -> Color32 {
theme::tint(color, share)
}
// ---- The grid ----
/// How wide a panel is that spans `span` of the `columns` columns of a row.
pub fn span_width(ui: &Ui, columns: usize, span: usize) -> f32 {
let all = ui.available_rect_before_wrap().width();
span_of(all, columns, span)
}
/// The same, from the row's width instead of a `Ui`.
pub fn span_of(row_width: f32, columns: usize, span: usize) -> f32 {
let gaps = space::PANEL_GAP;
let one = (row_width - gaps * (columns as f32 - 1.0)) / columns as f32;
one * span as f32 + gaps * (span as f32 - 1.0)
}
/// Where the panels of a row go: one rectangle per entry of `spans` (each the
/// number of columns the panel spans), all `height` tall, starting at the
/// cursor. Nothing is allocated yet; [`end_row`] does that.
pub fn cells(ui: &Ui, height: f32, spans: &[usize]) -> Vec<Rect> {
let columns: usize = spans.iter().sum();
let top_left = ui.cursor().min;
let mut left = top_left.x;
spans
.iter()
.map(|span| {
let width = span_width(ui, columns, *span);
let rect = Rect::from_min_size(Pos2::new(left, top_left.y), egui::vec2(width, height));
left += width + space::PANEL_GAP;
rect
})
.collect()
}
/// Close a row of panels drawn at `rects`: the cursor moves below the tallest.
pub fn end_row(ui: &mut Ui, rects: &[Rect]) {
let bottom = crate::fmt::lowest(rects.iter().map(|rect| rect.bottom()), ui.cursor().top());
let left = rects.first().map_or(ui.cursor().left(), |rect| rect.left());
ui.allocate_rect(
Rect::from_min_max(Pos2::new(left, ui.cursor().top()), Pos2::new(ui.cursor().right(), bottom)),
Sense::hover(),
);
ui.add_space(space::PANEL_GAP);
}
/// A hairline across the panel at the cursor.
pub fn rule(ui: &mut Ui) {
let (rect, _) = ui.allocate_exact_size(
egui::vec2(ui.available_rect_before_wrap().width(), 1.0),
Sense::hover(),
);
ui.painter()
.hline(rect.x_range(), rect.top() + 0.5, Stroke::new(1.0, p(ui).border));
}
// ---- Panels and cards ----
/// A panel with a title, at `rect`: no fill and no box, a hairline across its top.
/// It comes out at least as tall as `rect`; the rect it took is returned second.
pub fn panel<R>(ui: &mut Ui, rect: Rect, title: &str, body: impl FnOnce(&mut Ui) -> R) -> (R, Rect) {
let text = theme::title(ui, title).text().to_owned();
panel_titled(
ui,
rect,
|ui| {
ui.add(egui::Label::new(theme::title(ui, text)).truncate());
},
body,
)
}
/// [`panel`] with the title drawn by `title`: one line, `UNDER_TITLE` under it.
pub fn panel_titled<R>(
ui: &mut Ui,
rect: Rect,
title: impl FnOnce(&mut Ui),
body: impl FnOnce(&mut Ui) -> R,
) -> (R, Rect) {
let p = p(ui);
let pad = egui::vec2(space::PANEL_PADDING, space::PANEL_PAD_Y);
let mut inner = ui.new_child(
egui::UiBuilder::new()
.max_rect(rect.shrink2(pad))
.layout(Layout::top_down(Align::Min)),
);
inner.set_width((rect.width() - 2.0 * pad.x).max(0.0));
inner.set_min_height((rect.height() - 2.0 * pad.y).max(0.0));
inner.spacing_mut().item_spacing = egui::vec2(space::ITEM, space::LINE);
title(&mut inner);
inner.add_space(space::UNDER_TITLE);
let value = body(&mut inner);
let taken = inner.min_rect().expand2(pad);
ui.painter().hline(taken.x_range(), taken.top() + 0.5, Stroke::new(1.0, p.border));
(value, taken)
}
/// A message that must be noticed: the bad colour as a tint and a border, on
/// the panel colour.
pub fn banner(ui: &mut Ui, text: RichText, color: Color32) {
let p = p(ui);
let width = ui.available_rect_before_wrap().width();
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, 40.0), Sense::hover());
ui.painter().rect(
rect,
space::CONTROL_RADIUS,
tint(color, 0.14),
Stroke::new(1.0, tint(color, 0.5)),
StrokeKind::Inside,
);
let galley = galley(
ui,
text.strong().font(theme::semibold(px::BODY)),
true,
width - 2.0 * space::PANEL_PADDING,
);
ui.painter().galley(
Pos2::new(rect.left() + space::PANEL_PADDING, rect.center().y - galley.size().y / 2.0),
galley,
p.text,
);
}
/// The title of a panel that opens and closes when clicked. `open` is read and
/// written through `toggle`; returns whether it is open after the click.
pub fn toggling_title(ui: &mut Ui, title: &str, open: &mut bool) -> bool {
let p = p(ui);
let width = ui.available_rect_before_wrap().width();
let (rect, response) = ui.allocate_exact_size(egui::vec2(width, space::ROW), Sense::click());
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, title));
if response.clicked() {
*open = !*open;
}
let painter = ui.painter();
let color = if response.hovered() { p.text } else { p.muted };
let galley = galley(ui, theme::title(ui, title).color(color), false, f32::INFINITY);
painter.galley(
Pos2::new(rect.left(), rect.center().y - galley.size().y / 2.0),
galley,
color,
);
// A small chevron at the right: down when open, right when closed.
let at = Pos2::new(rect.right() - 4.0, rect.center().y);
let stroke = Stroke::new(1.5, p.muted);
let points = if *open {
vec![
Pos2::new(at.x - 4.0, at.y - 2.0),
at,
Pos2::new(at.x + 4.0, at.y - 2.0),
]
} else {
vec![
Pos2::new(at.x - 2.0, at.y - 4.0),
at,
Pos2::new(at.x - 2.0, at.y + 4.0),
]
};
painter.add(Shape::line(points, stroke));
*open
}
/// One cell of the counter strip: a small upper-case label, the number in mono, one line of
/// small print and the change against the period before. Exactly `rect`; a hairline stands at
/// its left unless it is the first of its row.
pub fn card(ui: &mut Ui, rect: Rect, first: bool, label: &str, number: &str, detail: &str, change: RichText, color: Color32) {
let p = p(ui);
ui.allocate_rect(rect, Sense::hover());
let inset = if first { 0.0 } else { 16.0 };
if !first {
ui.painter().vline(rect.left() + 0.5, rect.y_range().shrink(10.0), Stroke::new(1.0, p.grid));
}
let inner_rect = Rect::from_min_max(
Pos2::new(rect.left() + inset, rect.top() + 10.0),
Pos2::new(rect.right() - 8.0, rect.bottom() - 6.0),
);
let mut inner = ui.new_child(egui::UiBuilder::new().max_rect(inner_rect).layout(Layout::top_down(Align::Min)));
inner.set_width(inner_rect.width());
inner.spacing_mut().item_spacing = egui::vec2(space::ITEM, 1.0);
inner.add(egui::Label::new(theme::title(ui, label)).truncate());
inner.add(
egui::Label::new(
RichText::new(number)
.font(theme::number_font(px::CARD_NUMBER))
.color(color),
)
.truncate(),
);
let detail_label = inner.add(egui::Label::new(theme::small(ui, detail)).truncate());
if !detail.is_empty() {
detail_label.on_hover_text(detail);
}
inner.add(egui::Label::new(change).truncate());
}
// ---- Controls ----
/// One segmented control: `labels` side by side in one pill, the `chosen` one
/// marked with the accent. Returns the segment that was clicked.
pub fn segmented(ui: &mut Ui, id_salt: &'static str, labels: &[&str], chosen: usize) -> Option<usize> {
let p = p(ui);
let font = theme::medium(px::BODY);
let widths: Vec<f32> = labels
.iter()
.map(|label| text_width(ui, label, font.clone()) + 2.0 * space::CONTROL_PAD)
.collect();
let total: f32 = widths.iter().sum();
let (rect, _) = ui.allocate_exact_size(egui::vec2(total, space::CONTROL_HEIGHT), Sense::hover());
let painter = ui.painter();
painter.rect(
rect,
space::CONTROL_RADIUS,
p.track,
Stroke::new(1.0, p.border),
StrokeKind::Inside,
);
let mut left = rect.left();
let mut clicked = None;
for (index, (label, width)) in labels.iter().zip(&widths).enumerate() {
let segment = Rect::from_min_max(Pos2::new(left, rect.top()), Pos2::new(left + width, rect.bottom()));
let response = ui
.interact(segment, ui.scope_id().with(id_salt).with(index), Sense::click())
.on_hover_cursor(egui::CursorIcon::PointingHand);
let selected = index == chosen;
let fill = if selected {
p.accent
} else if response.hovered() {
p.hover
} else {
Color32::TRANSPARENT
};
if selected || response.hovered() {
painter.rect_filled(segment.shrink2(egui::vec2(1.0, 1.0)), space::CONTROL_RADIUS - 2.0, fill);
}
if index > 0 && !selected && index - 1 != chosen {
painter.vline(segment.left() + 0.5, segment.y_range().shrink(7.0), Stroke::new(1.0, p.border));
}
let color = if selected {
p.on_accent
} else if response.hovered() {
p.text
} else {
p.muted
};
painter.text(segment.center(), Align2::CENTER_CENTER, *label, font.clone(), color);
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, selected, *label));
if response.clicked() {
clicked = Some(index);
}
left += width;
}
clicked
}
// ---- Tables ----
/// What one cell of a [`table`] holds.
pub enum Cell {
Text(RichText),
/// A colour square, then text: the entry of a legend.
Marked(Color32, RichText),
/// A hit-rate bar for `hits` out of `hits + misses`; its column is fixed width.
Bar(u64, u64),
}
/// A table that lives inside its panel: columns as wide as what they hold, the
/// first column taking the slack; numbers in mono, right-aligned when the head
/// is; rows 24 px, a hairline between them; the head in the panel-title style.
/// A cell whose text does not fit is cut, and shows all of it on hover.
pub fn table(ui: &mut Ui, head: &[&str], rows: &[Vec<Cell>]) {
let p = p(ui);
let width = ui.available_rect_before_wrap().width();
let columns = head.len().max(rows.first().map_or(0, |row| row.len()));
let pad = space::CELL_PAD;
let title_font = theme::title_font();
let mut natural: Vec<f32> = head
.iter()
.map(|text| {
text_width(ui, &text.to_uppercase(), title_font.clone()) + 2.0 * pad
+ text.chars().count() as f32 * space::TITLE_SPACING
})
.collect();
natural.resize(columns, 0.0);
let mut galleys: Vec<Vec<(Option<Arc<Galley>>, String)>> = Vec::with_capacity(rows.len());
for row in rows {
let mut line = Vec::with_capacity(columns);
for (column, cell) in row.iter().enumerate() {
match cell {
Cell::Marked(_, text) | Cell::Text(text) => {
let galley = galley(ui, text.clone(), false, f32::INFINITY);
let mark = if matches!(cell, Cell::Marked(..)) {
theme::drawing::LEGEND_SWATCH + 6.0
} else {
0.0
};
natural[column] = natural[column].max(galley.size().x + 2.0 * pad + mark);
line.push((Some(galley), text.text().to_owned()));
}
Cell::Bar(..) => {
natural[column] = natural[column].max(theme::drawing::HIT_BAR + 2.0 * pad);
line.push((None, String::new()));
}
}
}
galleys.push(line);
}
// The label column takes the slack, and gives first when the table is too
// wide (after a bar column, which can shrink to a stub).
// The table reaches `pad` past both edges, so the first column's text and the last
// column's numbers line up with the panel's own edges.
let width_cells = width + 2.0 * pad;
let whole: f32 = natural.iter().sum();
let slack = width_cells - whole;
if slack >= 0.0 {
natural[0] += slack;
} else {
let bar = rows.first().and_then(|row| {
row.iter().position(|cell| matches!(cell, Cell::Bar(..)))
});
let mut missing = -slack;
if let Some(bar) = bar {
let give = missing.min((natural[bar] - 28.0).max(0.0));
natural[bar] -= give;
missing -= give;
}
let give = missing.min((natural[0] - 2.0 * pad - space::LABEL_MIN).max(0.0));
natural[0] -= give;
missing -= give;
if missing > 0.0 && whole > 0.0 {
for size in &mut natural {
*size -= missing * *size / whole;
}
}
}
let lefts: Vec<f32> = natural
.iter()
.scan(ui.cursor().left() - pad, |left, size| {
let at = *left;
*left += size;
Some(at)
})
.collect();
let height = space::ROW * (rows.len() + usize::from(!head.is_empty())) as f32;
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), Sense::hover());
let painter = ui.painter().with_clip_rect(rect);
let cell_rect = |column: usize, top: f32| {
Rect::from_min_max(
Pos2::new(lefts[column], top),
Pos2::new(lefts[column] + natural[column], top + space::ROW),
)
};
let put = |ui: &mut Ui, place: Rect, galley: &Arc<Galley>, text: &str, right: bool, id: egui::Id| {
let fits = galley.size().x + 2.0 * pad <= place.width() + 0.5;
let x = if right { place.right() - pad - galley.size().x } else { place.left() + pad };
let pos = Pos2::new(x, place.center().y - galley.size().y / 2.0);
let clip = place.intersect(ui.clip_rect());
ui.painter().with_clip_rect(clip).galley(pos, galley.clone(), p.text);
if !fits {
ui.interact(place, id, Sense::hover()).on_hover_text(text.to_owned());
}
};
let mut top = rect.top();
if !head.is_empty() {
for (column, text) in head.iter().enumerate() {
let place = cell_rect(column, top);
if text.is_empty() {
continue;
}
let galley = ui.painter().layout_no_wrap(text.to_uppercase(), title_font.clone(), p.muted);
put(ui, place, &galley, text, column > 0, ui.scope_id().with(("head", column)));
}
painter.hline(rect.x_range(), top.round() + space::ROW + 0.5, Stroke::new(1.0, p.border));
top += space::ROW;
}
// The rows start under the head, or at the top when there is none.
let first = top;
for (index, (row, line)) in rows.iter().zip(&galleys).enumerate() {
top = first + index as f32 * space::ROW;
if index + 1 < rows.len() {
painter.hline(rect.x_range(), top.round() + space::ROW + 0.5, Stroke::new(1.0, p.grid));
}
for (column, cell) in row.iter().enumerate() {
let place = cell_rect(column, top);
match cell {
Cell::Text(_) => {
let (galley, text) = &line[column];
if let Some(galley) = galley {
put(ui, place, galley, text, column > 0, ui.scope_id().with(("cell", index, column)));
}
}
Cell::Marked(color, _) => {
let side = theme::drawing::LEGEND_SWATCH;
let square = Rect::from_center_size(
Pos2::new(place.left() + pad + side / 2.0, place.center().y),
egui::vec2(side, side),
);
ui.painter().rect_filled(square, 0.0, *color);
let (galley, text) = &line[column];
if let Some(galley) = galley {
let text_place = Rect::from_min_max(
Pos2::new(place.left() + pad + side + 6.0, place.top()),
place.max,
);
put(ui, text_place, galley, text, false, ui.scope_id().with(("cell", index, column)));
}
}
Cell::Bar(hits, misses) => {
// As wide as its column, which shrinks before the text does.
let bar = Rect::from_min_size(
Pos2::new(place.left() + pad, place.center().y - theme::drawing::HIT_BAR_HEIGHT / 2.0),
egui::vec2((place.width() - 2.0 * pad).max(0.0), theme::drawing::HIT_BAR_HEIGHT),
);
hit_bar(ui, bar, *hits, *misses);
}
}
}
}
}
/// A bar filled from the left to `fraction` of its width (0 to 1), always `height` tall.
pub fn meter(ui: &mut Ui, height: f32, fraction: f64, fill: Color32) {
let width = ui.available_rect_before_wrap().width();
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), Sense::hover());
fill_bar(ui, rect, fraction, fill);
}
/// The same, in a rectangle already chosen.
pub fn fill_bar(ui: &mut Ui, rect: Rect, fraction: f64, fill: Color32) {
let p = p(ui);
let painter = ui.painter();
painter.rect_filled(rect, 0.0, p.track);
let width = rect.width() * fraction.clamp(0.0, 1.0) as f32;
if width > 0.5 {
painter.rect_filled(
Rect::from_min_max(rect.min, Pos2::new(rect.left() + width, rect.bottom())),
0.0,
fill,
);
}
}
/// One bar split into coloured parts. The parts fill the whole width when
/// their counts add up to `total`; a part with no count gets no width. What
/// each part holds shows on hover.
pub fn stacked_bar(ui: &mut Ui, parts: &[(&'static str, u64, Color32)], total: u64) {
let p = p(ui);
let width = ui.available_rect_before_wrap().width();
let (rect, response) = ui.allocate_exact_size(
egui::vec2(width, theme::drawing::STACKED_BAR),
Sense::hover(),
);
let painter = ui.painter();
painter.rect_filled(rect, 0.0, p.track);
let mut x = rect.left();
let mut tip = String::new();
for (name, part, color) in parts {
let width = if total > 0 { rect.width() * *part as f64 as f32 / total as f32 } else { 0.0 };
if width > 0.0 {
let part_rect = Rect::from_min_max(Pos2::new(x, rect.top()), Pos2::new(x + width, rect.bottom()));
painter.rect_filled(part_rect, 0.0, *color);
x += width;
tip.push_str(&format!(
"{name}: {} ({})\n",
crate::fmt::count(*part),
crate::fmt::share(*part, total)
));
}
}
if !tip.is_empty() {
response.on_hover_text(tip.trim_end());
}
}
/// A short bar showing hits (in the "from cache" colour) against misses.
pub fn hit_bar(ui: &mut Ui, rect: Rect, hits: u64, misses: u64) {
let p = p(ui);
let painter = ui.painter();
painter.rect_filled(rect, 0.0, p.track);
let total = hits + misses;
if total > 0 {
let hit_width = rect.width() * hits as f32 / total as f32;
painter.rect_filled(
Rect::from_min_max(rect.min, Pos2::new(rect.left() + hit_width, rect.bottom())),
0.0,
p.from_cache,
);
}
}
/// A trend line one point per bucket, drawn in a strip `height` tall. `None`
/// points break the line, so a gap never looks like a zero. `top` is the value
/// drawn at the top of the strip.
pub fn sparkline(ui: &mut Ui, height: f32, values: &[Option<f64>], top: f64, color: Color32) {
let p = p(ui);
let width = ui.available_rect_before_wrap().width();
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), Sense::hover());
let painter = ui.painter();
painter.hline(rect.x_range(), rect.bottom() - 0.5, Stroke::new(1.0, p.grid));
if values.is_empty() || top <= 0.0 {
return;
}
let at = |index: usize, value: f64| {
Pos2::new(
rect.left() + rect.width() * ((index as f32 + 0.5) / values.len() as f32),
rect.bottom() - (rect.height() * (value / top) as f32).min(rect.height()),
)
};
let mut run: Vec<Pos2> = Vec::new();
let flush = |run: &mut Vec<Pos2>, painter: &egui::Painter| match run.len() {
0 => {}
1 => {
painter.circle_filled(run[0], 2.0, color);
run.clear();
}
_ => {
painter.add(Shape::line(std::mem::take(run), Stroke::new(1.5, color)));
}
};
for (index, value) in values.iter().enumerate() {
match value {
Some(value) => run.push(at(index, *value)),
None => flush(&mut run, painter),
}
}
flush(&mut run, painter);
}
/// Where a value between a tenth of a millisecond and 100 seconds sits on a
/// scale that lets 0.7 ms and 8 s both be seen.
pub fn log_fraction(ms: f64) -> f64 {
const LOW: f64 = -1.0;
const HIGH: f64 = 5.0;
if !ms.is_finite() || ms <= 0.0 {
return 0.0;
}
let position = (ms.log10() - LOW) / (HIGH - LOW);
position.clamp(0.02, 1.0)
}
// ---- Chart keys ----
/// What an entry of a chart's key stands for.
pub enum Mark {
/// A bar.
Fill(Color32),
/// A line.
Line(Color32),
/// A dashed line: a reset.
Dashed(Color32),
/// Time nothing was recorded in.
Band,
}
/// The swatch for one entry of a chart's key.
pub fn key(ui: &mut Ui, mark: Mark) {
let p = p(ui);
let (rect, _) = ui.allocate_exact_size(
egui::vec2(theme::drawing::KEY_SWATCH, theme::drawing::KEY_SWATCH),
Sense::hover(),
);
let painter = ui.painter();
let left = Pos2::new(rect.left(), rect.center().y);
let right = Pos2::new(rect.right(), rect.center().y);
match mark {
Mark::Fill(color) => {
painter.rect_filled(rect.shrink(3.0), 2.0, color);
}
Mark::Line(color) => {
painter.add(Shape::line(vec![left, right], Stroke::new(2.0, color)));
}
Mark::Dashed(color) => {
painter.add(Shape::dashed_line(&[left, right], Stroke::new(1.5, color), 4.0, 3.0));
}
Mark::Band => {
painter.rect_filled(rect.shrink(3.0), 2.0, p.unrecorded);
painter.rect_stroke(rect.shrink(3.0), 2.0, Stroke::new(1.0, p.border), StrokeKind::Inside);
}
}
}
/// The key to a chart, drawn under it so it never sits on the data.
pub fn legend(ui: &mut Ui, entries: Vec<(Mark, String)>) {
ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing.x = 14.0;
for (mark, text) in entries {
key(ui, mark);
let response = ui.add(egui::Label::new(theme::small(ui, text.clone())).truncate());
response.on_hover_text(text);
}
});
}
+444
View File
@@ -0,0 +1,444 @@
//! Every colour, size, spacing and font of the page, in one place. A change of
//! taste is an edit in this file and nowhere else.
//!
//! The type is Inter and JetBrains Mono (both under the SIL Open Font License;
//! the licence files sit beside the font files in `assets/`).
use eframe::egui::{self, Color32, FontFamily, FontId, RichText, TextStyle};
pub static INTER_REGULAR_TTF: &[u8] = include_bytes!("../assets/Inter-Regular.ttf");
pub static INTER_MEDIUM_TTF: &[u8] = include_bytes!("../assets/Inter-Medium.ttf");
pub static INTER_SEMIBOLD_TTF: &[u8] = include_bytes!("../assets/Inter-SemiBold.ttf");
pub static MONO_REGULAR_TTF: &[u8] = include_bytes!("../assets/JetBrainsMono-Regular.ttf");
pub static MONO_MEDIUM_TTF: &[u8] = include_bytes!("../assets/JetBrainsMono-Medium.ttf");
const fn rgb(hex: u32) -> Color32 {
Color32::from_rgb((hex >> 16) as u8, (hex >> 8) as u8, hex as u8)
}
/// The colours of one theme. State colours (`good`, `warn`, `bad`) are used
/// only for state; the series colours only for the five outcomes of a compile.
#[derive(Clone, Copy, Debug)]
pub struct Palette {
pub dark: bool,
pub page: Color32,
pub panel: Color32,
pub border: Color32,
pub text: Color32,
pub muted: Color32,
/// Hairlines inside a panel: between table rows and across a chart.
pub grid: Color32,
/// The recessed track of a bar, and of a control.
pub track: Color32,
/// A control under the pointer.
pub hover: Color32,
pub good: Color32,
pub warn: Color32,
pub bad: Color32,
pub from_cache: Color32,
pub built: Color32,
pub not_cacheable: Color32,
pub unsupported: Color32,
pub not_compile: Color32,
/// Selected controls.
pub accent: Color32,
/// Text on the accent: what a selected control says.
pub on_accent: Color32,
/// Amber as text and lines: the hero figures and key lines (darker in the light theme to pass contrast).
pub hero: Color32,
/// The tint over time nothing was recorded in.
pub unrecorded: Color32,
/// The line of the mean, the median and the p90 on a build-time histogram.
pub mean: Color32,
pub median: Color32,
pub p90: Color32,
}
pub const DARK: Palette = Palette {
dark: true,
page: rgb(0x0f0f10),
panel: rgb(0x161617),
border: rgb(0x2a2a2c),
text: rgb(0xe8e6e1),
muted: rgb(0x8f8d87),
grid: rgb(0x1f1f21),
track: rgb(0x1b1b1d),
hover: rgb(0x1f1f21),
good: rgb(0x3ecf8e),
warn: rgb(0xffb000),
bad: rgb(0xff5f56),
from_cache: rgb(0x3ecf8e),
built: rgb(0x5b8def),
not_cacheable: rgb(0x8a8a8f),
unsupported: rgb(0x5f5f64),
not_compile: rgb(0x424246),
accent: rgb(0xffb000),
on_accent: rgb(0x0f0f10),
hero: rgb(0xffb000),
unrecorded: Color32::from_rgba_premultiplied(14, 14, 14, 14),
mean: rgb(0xe8e6e1),
median: rgb(0xffb000),
p90: rgb(0x8a8a8f),
};
pub const LIGHT: Palette = Palette {
dark: false,
page: rgb(0xf6f3ec),
panel: rgb(0xfffdf8),
border: rgb(0xd5cfc1),
text: rgb(0x1d1b17),
muted: rgb(0x6a655b),
grid: rgb(0xe6e1d6),
track: rgb(0xebe6da),
hover: rgb(0xe9e4d8),
good: rgb(0x1a8f5a),
warn: rgb(0xb87400),
bad: rgb(0xc62f26),
from_cache: rgb(0x1f9d63),
built: rgb(0x2f63d0),
not_cacheable: rgb(0x7a766c),
unsupported: rgb(0xa39f94),
not_compile: rgb(0xc2beb2),
accent: rgb(0xffb000),
on_accent: rgb(0x1d1b17),
hero: rgb(0x8a5600),
unrecorded: Color32::from_rgba_premultiplied(0, 0, 0, 16),
mean: rgb(0x1d1b17),
median: rgb(0x8a5600),
p90: rgb(0x7a766c),
};
/// The palette of the theme being drawn.
pub fn of(dark: bool) -> &'static Palette {
if dark {
&DARK
} else {
&LIGHT
}
}
/// The palette of the theme `ctx` is drawing in.
pub fn ctx(ctx: &egui::Context) -> &'static Palette {
of(ctx.theme() == egui::Theme::Dark)
}
/// The palette of the theme `ui` is drawing in.
pub fn ui(ui: &egui::Ui) -> &'static Palette {
ctx(ui.ctx())
}
/// A colour made see-through: `color` over the panel at `share` of its strength.
pub fn tint(color: Color32, share: f32) -> Color32 {
let alpha = (share.clamp(0.0, 1.0) * 255.0).round() as u8;
Color32::from_rgba_premultiplied(color.r(), color.g(), color.b(), alpha)
}
/// Font sizes in pixels. There are no others.
pub mod px {
/// Panel titles, table heads and small labels: upper case, letter-spaced.
pub const TITLE: f32 = 11.0;
/// Text, and the controls.
pub const BODY: f32 = 13.0;
/// Small print.
pub const SMALL: f32 = 11.0;
/// The number on a stat card.
pub const CARD_NUMBER: f32 = 22.0;
/// The three figures of the headline panel.
pub const HEADLINE: f32 = 56.0;
}
/// Space in pixels.
pub mod space {
pub const PAGE_MARGIN: f32 = 16.0;
/// Between panels, and between cards.
pub const PANEL_GAP: f32 = 24.0;
/// Between the controls of the top bar.
pub const TOOL_GAP: f32 = 8.0;
/// Panels have no side padding: their content lines up with the hairline above it.
pub const PANEL_PADDING: f32 = 0.0;
/// Room between a panel's top hairline and its title, and under its content.
pub const PANEL_PAD_Y: f32 = 12.0;
pub const PANEL_RADIUS: f32 = 0.0;
pub const CONTROL_RADIUS: f32 = 2.0;
/// Between items that follow each other in a panel.
pub const ITEM: f32 = 8.0;
/// Between lines of one paragraph.
pub const LINE: f32 = 3.0;
/// One table row.
pub const ROW: f32 = 24.0;
/// Space either side of the text in a table cell.
pub const CELL_PAD: f32 = 8.0;
/// The narrowest the label column of a table gets before its text is cut.
pub const LABEL_MIN: f32 = 72.0;
pub const CONTROL_HEIGHT: f32 = 24.0;
pub const CONTROL_PAD: f32 = 9.0;
pub const TITLE_SPACING: f32 = 0.8;
pub const TOOLBAR_NOTE_WIDTH: f32 = 150.0;
/// Between a raw counter's key and its value.
pub const KEY_VALUE_GAP: f32 = 16.0;
/// Room under a title before the panel's content.
pub const UNDER_TITLE: f32 = 8.0;
/// Room between titled parts of one panel.
pub const BETWEEN_PARTS: f32 = 14.0;
}
/// How the page is laid out, in pixels of window width.
pub mod layout {
/// From this width the page has three columns of panels.
pub const THREE_COLUMNS_FROM: f32 = 1100.0;
/// From this width it has two; below it, one.
pub const TWO_COLUMNS_FROM: f32 = 700.0;
/// How many columns of key/value lines the raw counters run in, per page column.
pub const RAW_LINE_WIDTH: f32 = 400.0;
pub const TOOLBAR_HEIGHT: f32 = 24.0;
/// The hero band on a wide page: caption row, one row of figures and the storage line.
pub const HEADLINE_HEIGHT: f32 = 296.0;
/// A hero figure: the number, its caption, the trend line and two lines of small print.
pub const FIGURE_HEIGHT: f32 = 176.0;
/// One row of the counter strip.
pub const STRIP_ROW_HEIGHT: f32 = 92.0;
/// "Where compiles went": its bar, legend and the "of the built" line.
pub const WHERE_FIXED_HEIGHT: f32 = 212.0;
/// "Why compiles were not cacheable" needs this much beside its reasons: padding, title and the room under it.
pub const REASONS_FIXED_HEIGHT: f32 = 56.0;
/// From this panel width the "By language" table has room for its hit-rate bars.
pub const LANGUAGE_BARS_FROM: f32 = 380.0;
/// "By language" needs this much beside its rows.
pub const LANGUAGES_FIXED_HEIGHT: f32 = 50.0;
/// "Speed" needs this much beside its histograms.
pub const SPEED_FIXED_HEIGHT: f32 = 240.0;
/// "Speed" needs this much per language with a histogram.
pub const HISTOGRAM_HEIGHT: f32 = 85.0;
/// A panel of one time chart: padding, title, plot and legend.
pub const CHART_PANEL_HEIGHT: f32 = 306.0;
}
/// Drawings inside panels, in pixels.
pub mod drawing {
pub const CHART_HEIGHT: f32 = 240.0;
/// The trend line under a headline figure.
pub const SPARKLINE: f32 = 36.0;
pub const BUILD_HISTOGRAM: f32 = 44.0;
pub const BUILD_AXIS: f32 = 14.0;
pub const STACKED_BAR: f32 = 22.0;
pub const SPEED_BAR: f32 = 10.0;
pub const USAGE_BAR: f32 = 4.0;
pub const HIT_BAR: f32 = 72.0;
pub const HIT_BAR_HEIGHT: f32 = 6.0;
pub const LEGEND_SWATCH: f32 = 10.0;
pub const KEY_SWATCH: f32 = 14.0;
pub const SEVERITY_DOT: f32 = 8.0;
/// Share of the range's length left empty either side of a chart, so the
/// first and last time label sit inside the plot.
pub const CHART_SIDE_AIR: f64 = 0.035;
}
/// A hit rate is good from this share of compiles, and worth a look from the next.
pub mod state {
pub const HIT_RATE_GOOD: f64 = 0.7;
pub const HIT_RATE_WARN: f64 = 0.4;
/// A cache this full is shown in the bad colour.
pub const CACHE_FULL: f64 = 0.95;
}
// The font families, by name.
pub const REGULAR: &str = "inter-regular";
pub const MEDIUM: &str = "inter-medium";
pub const SEMIBOLD: &str = "inter-semibold";
pub const MONO: &str = "jetbrains-mono";
pub const MONO_MEDIUM: &str = "jetbrains-mono-medium";
// The text styles beyond egui's own, by name.
pub const TITLE_STYLE: &str = "title";
pub const CARD_STYLE: &str = "card-number";
pub const HEADLINE_STYLE: &str = "headline-number";
pub fn medium_family() -> FontFamily {
FontFamily::Name(MEDIUM.into())
}
pub fn semibold_family() -> FontFamily {
FontFamily::Name(SEMIBOLD.into())
}
pub fn mono_medium_family() -> FontFamily {
FontFamily::Name(MONO_MEDIUM.into())
}
/// Text of `size` in Inter Medium.
pub fn medium(size: f32) -> FontId {
FontId::new(size, medium_family())
}
/// Text of `size` in Inter SemiBold.
pub fn semibold(size: f32) -> FontId {
FontId::new(size, semibold_family())
}
/// A number of `size`: JetBrains Mono Medium.
pub fn number_font(size: f32) -> FontId {
FontId::new(size, mono_medium_family())
}
/// The font of panel titles and table heads.
pub fn title_font() -> FontId {
semibold(px::TITLE)
}
fn families() -> egui::FontDefinitions {
use std::sync::Arc;
let mut fonts = egui::FontDefinitions::default();
for (name, data) in [
(REGULAR, INTER_REGULAR_TTF),
(MEDIUM, INTER_MEDIUM_TTF),
(SEMIBOLD, INTER_SEMIBOLD_TTF),
(MONO, MONO_REGULAR_TTF),
(MONO_MEDIUM, MONO_MEDIUM_TTF),
] {
fonts
.font_data
.insert(name.to_owned(), Arc::new(egui::FontData::from_static(data)));
}
fonts
.families
.entry(FontFamily::Proportional)
.or_default()
.insert(0, REGULAR.to_owned());
fonts
.families
.entry(FontFamily::Monospace)
.or_default()
.insert(0, MONO.to_owned());
fonts
.families
.insert(medium_family(), vec![MEDIUM.to_owned()]);
fonts
.families
.insert(semibold_family(), vec![SEMIBOLD.to_owned()]);
fonts
.families
.insert(mono_medium_family(), vec![MONO_MEDIUM.to_owned()]);
fonts
}
fn text_styles() -> std::collections::BTreeMap<TextStyle, FontId> {
[
(TextStyle::Small, FontId::proportional(px::SMALL)),
(TextStyle::Body, FontId::proportional(px::BODY)),
(TextStyle::Button, medium(px::BODY)),
(TextStyle::Heading, semibold(px::BODY)),
(TextStyle::Monospace, FontId::monospace(px::BODY)),
(TextStyle::Name(TITLE_STYLE.into()), title_font()),
(
TextStyle::Name(CARD_STYLE.into()),
number_font(px::CARD_NUMBER),
),
(
TextStyle::Name(HEADLINE_STYLE.into()),
number_font(px::HEADLINE),
),
]
.into_iter()
.collect()
}
fn visuals(p: &Palette) -> egui::Visuals {
use egui::style::WidgetVisuals;
use egui::{CornerRadius, Stroke};
let mut visuals = if p.dark {
egui::Visuals::dark()
} else {
egui::Visuals::light()
};
visuals.override_text_color = Some(p.text);
visuals.panel_fill = p.page;
visuals.window_fill = p.panel;
visuals.window_stroke = Stroke::new(1.0, p.border);
visuals.extreme_bg_color = p.track;
visuals.faint_bg_color = p.hover;
visuals.selection.bg_fill = tint(p.accent, 0.35);
visuals.selection.stroke = Stroke::new(1.0, p.accent);
visuals.hyperlink_color = p.accent;
visuals.warn_fg_color = p.warn;
visuals.error_fg_color = p.bad;
let control = |fill, stroke, text: Color32| WidgetVisuals {
corner_radius: CornerRadius::same(space::CONTROL_RADIUS as u8),
bg_fill: fill,
weak_bg_fill: fill,
bg_stroke: Stroke::new(1.0, stroke),
fg_stroke: Stroke::new(1.0, text),
expansion: 0.0,
};
visuals.widgets.noninteractive = control(p.track, p.border, p.muted);
visuals.widgets.inactive = control(Color32::TRANSPARENT, p.border, p.text);
visuals.widgets.hovered = control(p.hover, p.muted, p.text);
visuals.widgets.active = control(tint(p.accent, 0.25), p.accent, p.text);
visuals.widgets.open = control(p.hover, p.muted, p.text);
visuals
}
/// Put the fonts, text styles, spacing and both themes' colours on the page.
pub fn install(ctx: &egui::Context) {
ctx.set_fonts(families());
ctx.all_styles_mut(|style| {
style.text_styles = text_styles();
style.spacing.item_spacing = egui::vec2(space::ITEM, space::LINE);
style.spacing.button_padding = egui::vec2(8.0, 2.0);
style.spacing.interact_size.y = space::CONTROL_HEIGHT;
style.spacing.indent = 12.0;
style.visuals = visuals(of(style.visuals.dark_mode));
});
}
/// A panel title: 11 px, upper case, letter-spaced, muted.
pub fn title(scope: &egui::Ui, text: impl AsRef<str>) -> RichText {
RichText::new(text.as_ref().to_uppercase())
.font(title_font())
.color(ui(scope).muted)
.extra_letter_spacing(space::TITLE_SPACING)
}
/// Small print in the muted colour.
pub fn small(scope: &egui::Ui, text: impl Into<String>) -> RichText {
RichText::new(text.into())
.font(FontId::proportional(px::SMALL))
.color(ui(scope).muted)
}
/// Text in the body size.
pub fn body(text: impl Into<String>) -> RichText {
RichText::new(text.into()).font(FontId::proportional(px::BODY))
}
/// Text in the body size, a little heavier.
pub fn strong(text: impl Into<String>) -> RichText {
RichText::new(text.into()).font(semibold(px::BODY))
}
/// A number in the body size, in the mono font.
pub fn number(text: impl Into<String>) -> RichText {
RichText::new(text.into()).font(number_font(px::BODY))
}
/// The colour of a hit rate: good, worth a look, or bad.
pub fn hit_rate_color(rate: Option<f64>, p: &Palette) -> Color32 {
match rate {
Some(rate) if rate >= state::HIT_RATE_GOOD => p.good,
Some(rate) if rate >= state::HIT_RATE_WARN => p.warn,
Some(_) => p.bad,
None => p.muted,
}
}
/// How many columns of panels the page has at `width`.
pub fn columns(width: f32) -> usize {
if width >= layout::THREE_COLUMNS_FROM {
3
} else if width >= layout::TWO_COLUMNS_FROM {
2
} else {
1
}
}
+258
View File
@@ -0,0 +1,258 @@
//! Where compiles went: one bar split by outcome, with a legend of counts and
//! shares; what happened inside the built share; and why some could not be
//! cached. How each language fared is its own panel ([`languages`]).
use std::sync::Arc;
use eframe::egui::{self, Color32, Sense, Stroke, Ui};
use eframe::epaint::text::Galley;
use sccache_dash_api::{NotCached, View};
use crate::disclosure;
use crate::fmt;
use crate::style::{self, Cell};
use crate::theme;
pub fn section(ui: &mut Ui, view: &View) {
let totals = &view.totals;
let p = theme::ui(ui);
// Five shares of every compiler call; timeouts, cache errors and forced
// recaches are inside the built share, as sccache counts them.
let parts: [(&'static str, u64, Color32); 5] = [
("From cache", totals.hits, p.from_cache),
("Built", totals.misses, p.built),
("Not cacheable", totals.not_cacheable, p.not_cacheable),
("Unsupported compiler", totals.unsupported_compiler, p.unsupported),
("Not a compile", totals.not_compile, p.not_compile),
];
let all: u64 = parts.iter().map(|(_, count, _)| count).sum();
let percents = fmt::shares(&parts.iter().map(|(_, count, _)| *count).collect::<Vec<_>>());
style::stacked_bar(ui, &parts, all);
ui.add_space(6.0);
let legend: Vec<Vec<Cell>> = parts
.iter()
.zip(&percents)
.map(|((name, count, color), percent)| {
vec![
Cell::Marked(*color, theme::body(*name)),
Cell::Text(theme::number(fmt::count(*count))),
Cell::Text(theme::number(format!("{percent}%"))),
]
})
.collect();
style::table(ui, &[], &legend);
ui.add_space(theme::space::ITEM);
ui.add(egui::Label::new(
theme::small(
ui,
format!(
"Of the built: {} timeouts, {} cache errors, {} forced recaches, {} failed to compile",
fmt::count(totals.timeouts),
fmt::count(totals.errors()),
fmt::count(totals.forced_recaches),
fmt::count(totals.compile_fails)
),
),
));
}
/// One reason laid out for a width: its line, and the two small paragraphs when it is open.
struct Block {
name: Arc<Galley>,
count: Arc<Galley>,
share: Arc<Galley>,
/// `None` while the reason is closed.
meaning: Option<Arc<Galley>>,
/// `None` when closed, or when sccache gives nothing to do.
action: Option<Arc<Galley>>,
/// The line: at least a control tall, taller when the name wraps.
row: f32,
open: bool,
}
impl Block {
fn entry(&self) -> disclosure::Entry {
disclosure::Entry {
row: self.row,
open: self.open,
meaning: self.meaning.as_ref().map_or(0.0, |g| g.size().y),
action: self.action.as_ref().map(|g| g.size().y),
}
}
}
/// How far the name is from the numbers, and from the dot.
const NAME_GAP: f32 = 8.0;
/// The side of the chevron's triangle box.
const CHEVRON: f32 = 8.0;
/// The hairline between two lines.
const SEPARATOR: f32 = 1.0;
/// Where a reason remembers whether it is open.
fn open_id(reason: &str) -> egui::Id {
egui::Id::new(("reason-open", reason))
}
fn is_open(ctx: &egui::Context, reason: &NotCached) -> bool {
let stored = ctx.data(|data| data.get_temp::<bool>(open_id(&reason.reason)));
disclosure::is_open(stored, reason.fixable)
}
/// Lay every reason out in `width`; counts and shares line up in columns, the name takes the rest.
fn blocks(ui: &Ui, view: &View, width: f32) -> Vec<Block> {
let number = |text: String| style::galley(ui, theme::number(text), false, f32::INFINITY);
let numbers: Vec<(Arc<Galley>, Arc<Galley>)> = view
.not_cached
.iter()
.map(|r| (number(fmt::count(r.count)), number(fmt::share(r.count, view.totals.not_cacheable))))
.collect();
let widest = |pick: fn(&(Arc<Galley>, Arc<Galley>)) -> &Arc<Galley>| {
numbers.iter().map(|n| pick(n).size().x).fold(0.0, f32::max)
};
let (count_width, share_width) = (widest(|n| &n.0), widest(|n| &n.1));
let indent = theme::drawing::SEVERITY_DOT + NAME_GAP;
let name_width = (width - indent - count_width - share_width - CHEVRON - 3.0 * NAME_GAP).max(40.0);
view.not_cached
.iter()
.zip(numbers)
.map(|(r, (count, share))| {
let name = style::galley(ui, theme::body(r.name.clone()), true, name_width);
let open = is_open(ui.ctx(), r);
let small = |text: &str| style::galley(ui, theme::small(ui, text), true, width - indent);
Block {
row: theme::space::CONTROL_HEIGHT.max(name.size().y + 2.0 * theme::space::ITEM),
name,
count,
share,
meaning: open.then(|| small(&r.meaning)),
action: (open && !r.action.is_empty()).then(|| small(&r.action)),
open,
}
})
.collect()
}
/// A triangle in the muted colour: pointing right when closed, down when open.
pub(crate) fn chevron(painter: &egui::Painter, center: egui::Pos2, open: bool, color: Color32) {
let h = CHEVRON / 2.0;
let points = if open {
vec![center + egui::vec2(-h, -h / 2.0), center + egui::vec2(h, -h / 2.0), center + egui::vec2(0.0, h / 2.0 + 1.0)]
} else {
vec![center + egui::vec2(-h / 2.0, -h), center + egui::vec2(-h / 2.0, h), center + egui::vec2(h / 2.0 + 1.0, 0.0)]
};
painter.add(egui::Shape::convex_polygon(points, color, Stroke::NONE));
}
/// "Why compiles were not cacheable": one line per reason, each with a dot (the warning
/// colour when a setting would fix it, the muted one when it is expected), its plain name,
/// its count and share, and a chevron. Clicking the line shows, in small print under it,
/// what it means and what to do; the reasons a setting would fix start open.
pub fn reasons(ui: &mut Ui, view: &View) {
if view.not_cached.is_empty() {
ui.label(theme::small(ui, "Every compile could be cached in this range."));
return;
}
let p = theme::ui(ui);
let width = ui.available_width();
let blocks = blocks(ui, view, width);
let indent = theme::drawing::SEVERITY_DOT + NAME_GAP;
// Every height is added by hand, so the list is as tall as `reasons_height` says.
ui.spacing_mut().item_spacing.y = 0.0;
for (index, (reason, block)) in view.not_cached.iter().zip(&blocks).enumerate() {
if index > 0 {
let (gap, _) = ui.allocate_exact_size(egui::vec2(width, SEPARATOR), Sense::hover());
ui.painter().rect_filled(gap, 0.0, p.grid);
}
let (row, response) = ui.allocate_exact_size(egui::vec2(width, block.row), Sense::click());
let response = response.on_hover_cursor(egui::CursorIcon::PointingHand);
response.widget_info(|| {
egui::WidgetInfo::labeled(egui::WidgetType::Button, true, reason.name.as_str())
});
if response.clicked() {
ui.ctx().data_mut(|data| data.insert_temp(open_id(&reason.reason), !block.open));
ui.ctx().request_repaint();
}
let painter = ui.painter();
if response.hovered() || response.has_focus() {
painter.rect_filled(row, theme::space::CONTROL_RADIUS, p.hover);
}
if response.has_focus() {
painter.rect_stroke(row, theme::space::CONTROL_RADIUS, Stroke::new(1.0, p.muted), egui::StrokeKind::Inside);
}
let side = theme::drawing::SEVERITY_DOT;
let dot = if reason.fixable { p.warn } else { p.not_cacheable };
let name_top = row.top() + (block.row - block.name.size().y) / 2.0;
painter.rect_filled(egui::Rect::from_center_size(egui::pos2(row.left() + side / 2.0, row.center().y), egui::vec2(side, side)), 0.0, dot);
painter.galley(egui::pos2(row.left() + indent, name_top), block.name.clone(), p.text);
let chevron_left = row.right() - CHEVRON;
chevron(painter, egui::pos2(chevron_left + CHEVRON / 2.0, row.center().y), block.open, p.muted);
let share_left = chevron_left - NAME_GAP - block.share.size().x;
let at = |galley: &Arc<Galley>, left: f32| {
egui::pos2(left, row.top() + (block.row - galley.size().y) / 2.0)
};
painter.galley(at(&block.share, share_left), block.share.clone(), p.text);
let count_left = share_left - NAME_GAP - block.count.size().x;
painter.galley(at(&block.count, count_left), block.count.clone(), p.text);
let mut opened = false;
for galley in block.meaning.iter().chain(block.action.as_ref()) {
ui.add_space(theme::space::LINE);
let (place, _) = ui.allocate_exact_size(egui::vec2(width, galley.size().y), Sense::hover());
ui.painter().galley(egui::pos2(place.left() + indent, place.top()), galley.clone(), p.muted);
opened = true;
}
if opened {
ui.add_space(theme::space::ITEM);
}
}
}
/// How tall "Why compiles were not cacheable" is in a panel `panel_width` wide.
pub fn reasons_height(ui: &Ui, view: &View, panel_width: f32) -> f32 {
let inner = panel_width - 2.0 * theme::space::PANEL_PADDING;
let entries: Vec<_> = blocks(ui, view, inner).iter().map(Block::entry).collect();
let list = disclosure::list_height(&entries, theme::space::LINE, theme::space::ITEM, SEPARATOR);
theme::layout::REASONS_FIXED_HEIGHT + list.max(theme::space::ROW)
}
/// "By language": one row per language, with hits, misses, errors, the hit rate
/// in its state colour, and a bar of hits against misses.
pub fn languages(ui: &mut Ui, view: &View) {
if view.languages.is_empty() {
ui.label(theme::small(ui, "No compiles were counted in this range."));
return;
}
let p = theme::ui(ui);
// The bar is the first thing to go where the columns are too tight to leave it room.
let with_bars = ui.available_rect_before_wrap().width() >= theme::layout::LANGUAGE_BARS_FROM;
let mut head = vec!["", "Hits", "Misses", "Errors", "Hit rate"];
if with_bars {
head.push("");
}
let mut rows: Vec<Vec<Cell>> = view
.languages
.iter()
.map(|language| {
let rate = crate::overtime::hit_rate(language.hits, language.misses);
vec![
Cell::Text(theme::strong(language.name.clone())),
Cell::Text(theme::number(fmt::count(language.hits))),
Cell::Text(theme::number(fmt::count(language.misses))),
Cell::Text(
theme::number(fmt::count(language.errors))
.color(if language.errors > 0 { p.bad } else { p.text }),
),
Cell::Text(
theme::number(fmt::percent(rate)).color(theme::hit_rate_color(rate, p)),
),
]
})
.collect();
if with_bars {
for (row, language) in rows.iter_mut().zip(&view.languages) {
row.push(Cell::Bar(language.hits, language.misses));
}
}
style::table(ui, &head, &rows);
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 253 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 226 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

+4
View File
@@ -8,3 +8,7 @@ test:
run: run:
cargo run -p sccache-dash cargo run -p sccache-dash
# Screenshots of the whole page at the 3, 2 and 1 column widths; read them before merging a page change.
shots url="http://127.0.0.1:8226/" out="target/shots":
prlimit --core=1:1 -- node scripts/shots.js {{url}} {{out}}
+5
View File
@@ -0,0 +1,5 @@
# Tools for building and running sccache-dash.
[tools]
# Builds the dashboard page (crates/ui) to WebAssembly. The release binary is
# downloaded; building trunk from source takes half an hour.
"ubi:trunk-rs/trunk" = "0.22.2"
+24
View File
@@ -0,0 +1,24 @@
// Screenshots of the whole page at each layout width (3, 2 and 1 column), read
// before any page change is merged. Usage: just shots [url] [out-dir]
const path = require('path');
const { execSync } = require('child_process');
const root = execSync('mise where npm:playwright 2>/dev/null || mise where playwright', { encoding: 'utf8' }).trim();
const { chromium } = require(path.join(root, 'node_modules/playwright'));
const [, , url = 'http://127.0.0.1:8226/', out = 'target/shots'] = process.argv;
(async () => {
require('fs').mkdirSync(out, { recursive: true });
const browser = await chromium.launch({
args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'],
});
for (const [width, height] of [[1400, 2600], [900, 3600], [390, 5600]]) {
// The page scrolls inside its canvas, so a tall window shows all of it.
const page = await browser.newPage({ viewport: { width, height }, colorScheme: 'dark' });
await page.goto(url);
await page.waitForTimeout(5000);
const file = path.join(out, `page-${width}.png`);
await page.screenshot({ path: file });
console.log(file);
await page.close();
}
await browser.close();
})().catch((error) => { console.error(error); process.exit(1); });