Compare commits

...
22 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
33 changed files with 3397 additions and 997 deletions

No files matched your search

+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"
);
}
+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.
+11 -1
View File
@@ -3,7 +3,10 @@
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="dark light" />
<title>sccache dash</title> <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" /> <link data-trunk rel="rust" data-bin="sccache-dash-ui" />
<style> <style>
/* The page is one canvas that fills the window and scrolls inside itself. */ /* The page is one canvas that fills the window and scrolls inside itself. */
@@ -13,7 +16,14 @@
height: 100dvh; height: 100dvh;
margin: 0; margin: 0;
overflow: hidden; overflow: hidden;
background: #111; /* 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 { canvas {
display: block; display: block;
+605 -275
View File
@@ -5,7 +5,9 @@ use std::time::Duration;
use eframe::egui; use eframe::egui;
use sccache_dash_api::{Range, View}; use sccache_dash_api::{Range, View};
use crate::disclosure;
use crate::fmt; use crate::fmt;
use crate::theme;
use crate::{cards, extras, net, overtime, problems, raw, speed, style, where_went}; use crate::{cards, extras, net, overtime, problems, raw, speed, style, where_went};
/// Refresh intervals offered, in seconds; zero means off. /// Refresh intervals offered, in seconds; zero means off.
@@ -86,12 +88,7 @@ impl Dashboard {
}; };
let ctx = &cc.egui_ctx; let ctx = &cc.egui_ctx;
ctx.set_theme(dashboard.theme.preference()); ctx.set_theme(dashboard.theme.preference());
ctx.all_styles_mut(|style| { theme::install(ctx);
style
.text_styles
.insert(egui::TextStyle::Small, egui::FontId::proportional(11.5));
style.spacing.item_spacing = egui::vec2(8.0, 4.0);
});
dashboard dashboard
} }
@@ -179,27 +176,44 @@ impl eframe::App for Dashboard {
} }
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { 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); controls(self, ui);
egui::CentralPanel::default().show(ui, |ui| { if let (Some(view), Some(error)) = (&self.view, &self.error) {
egui::ScrollArea::vertical() lost_contact(
.auto_shrink([false; 2]) ui.ctx(),
.show(ui, |ui| { error,
ui.add_space(8.0); view.generated_at,
let Self { ui.available_rect_before_wrap().width(),
range, );
view, }
error, egui::CentralPanel::default()
hidden_languages, .frame(
.. egui::Frame::NONE
} = self; .fill(theme::ctx(ui.ctx()).page)
match view { .inner_margin(egui::Margin::symmetric(
None => waiting(ui, error.as_deref(), self.refresh_secs), theme::space::PAGE_MARGIN as i8,
Some(view) => { theme::space::PAGE_MARGIN as i8,
page(ui, view, *range, error.as_deref(), hidden_languages) )),
)
.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 { if self.asking_zero {
zero_question(self, ui.ctx()); zero_question(self, ui.ctx());
@@ -232,114 +246,201 @@ fn remembered<T: serde::de::DeserializeOwned>(
storage.and_then(|storage| eframe::get_value(storage, key)) storage.and_then(|storage| eframe::get_value(storage, key))
} }
/// The row of controls that stays at the top of the page. 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) { fn controls(dashboard: &mut Dashboard, ui: &mut egui::Ui) {
let ctx = ui.ctx().clone(); let ctx = ui.ctx().clone();
let now = Dashboard::now(&ctx); let now = Dashboard::now(&ctx);
egui::Panel::top("controls").show(ui, |ui| { let gap = theme::space::TOOL_GAP;
ui.add_space(6.0); let margin = theme::space::PAGE_MARGIN;
ui.horizontal_wrapped(|ui| { let vertical = 10.0;
for range in Range::ALL { ui.add_space(vertical);
if ui let width = ui.available_rect_before_wrap().width() - 2.0 * margin;
.add(egui::Button::selectable( let medium = theme::medium(theme::px::BODY);
dashboard.range == range, let range_width: f32 = Range::ALL
range.code(), .iter()
)) .map(|range| style::text_width(ui, range.code(), medium.clone()) + 2.0 * theme::space::CONTROL_PAD)
.clicked() .sum();
{ let left_width = wordmark_width(ui) + 2.0 * theme::space::PANEL_GAP + range_width;
dashboard.range = range; let one_line = left_width + gap + actions_width(ui) <= width;
dashboard.settings_changed = true; let phone = width + 2.0 * theme::space::PAGE_MARGIN < theme::layout::TWO_COLUMNS_FROM;
dashboard.send(&ctx, Ask::View);
}
}
ui.add_space(8.0); let labels: Vec<&str> = Range::ALL.iter().map(|range| range.code()).collect();
let mut refresh_secs = dashboard.refresh_secs; let chosen = Range::ALL.iter().position(|range| *range == dashboard.range).unwrap_or(0);
egui::ComboBox::from_id_salt("refresh") ui.horizontal(|ui| {
.selected_text(fmt::refresh_label(refresh_secs)) ui.spacing_mut().item_spacing.x = gap;
.show_ui(ui, |ui| { ui.add_space(margin);
for secs in REFRESH_CHOICES { wordmark(ui);
ui.selectable_value(&mut refresh_secs, secs, fmt::refresh_label(secs)); ui.add_space(theme::space::PANEL_GAP - gap);
} if let Some(index) = style::segmented(ui, "range", &labels, chosen) {
}); if index != chosen {
if refresh_secs != dashboard.refresh_secs { dashboard.range = Range::ALL[index];
dashboard.refresh_secs = refresh_secs;
dashboard.settings_changed = true; dashboard.settings_changed = true;
}
if ui.button("Refresh").clicked() {
dashboard.send(&ctx, Ask::View); dashboard.send(&ctx, Ask::View);
} }
}
ui.add_space(8.0); if one_line {
for theme in ThemeChoice::ALL { ui.add_space((ui.available_width() - actions_width(ui) - margin).max(0.0));
if ui ui.allocate_ui_with_layout(
.add(egui::Button::selectable(dashboard.theme == theme, theme.name())) egui::vec2(actions_width(ui), theme::layout::TOOLBAR_HEIGHT),
.clicked() egui::Layout::left_to_right(egui::Align::Center),
{ |ui| actions(dashboard, ui, &ctx, now, gap),
dashboard.theme = theme; );
dashboard.settings_changed = true; }
ctx.set_theme(theme.preference()); });
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);
}
ui.add_space(8.0); /// Refresh, theme, Copy summary, Export JSON, Zero stats, and the message slot.
let online = dashboard.view.is_some(); fn actions(dashboard: &mut Dashboard, ui: &mut egui::Ui, ctx: &egui::Context, now: f64, gap: f32) {
let copy = ui.add_enabled(online, egui::Button::new("Copy summary")); ui.spacing_mut().item_spacing.x = gap;
if copy.clicked() { let mut refresh_secs = dashboard.refresh_secs;
if let Some(view) = &dashboard.view { egui::ComboBox::from_id_salt("refresh")
ctx.copy_text(view.summary_markdown.clone()); .selected_text(fmt::refresh_label(refresh_secs))
} .show_ui(ui, |ui| {
dashboard.flash("Summary copied", now); for secs in REFRESH_CHOICES {
ui.selectable_value(&mut refresh_secs, secs, fmt::refresh_label(secs));
} }
let export = ui.add_enabled(online, egui::Button::new("Export JSON")); });
if export.clicked() { if refresh_secs != dashboard.refresh_secs {
let note = net::download("/api/export").map_or_else( dashboard.refresh_secs = refresh_secs;
|error| format!("Export failed: {error}"), dashboard.settings_changed = true;
|()| "Export started".to_owned(), }
); if ui.button("Refresh").clicked() {
dashboard.flash(note, now); dashboard.send(ctx, Ask::View);
} }
let zeroing = dashboard
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 .pending
.as_ref() .as_ref()
.is_some_and(|(ask, _)| *ask == Ask::Zero); .is_some_and(|(ask, _)| *ask == Ask::View)
let zero = ui.add_enabled(online && !zeroing, egui::Button::new("Zero stats")); {
if zero.clicked() { ui.spinner();
dashboard.asking_zero = true; 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());
} }
},
// A fixed-size slot, so that messages come and go without moving the controls. );
ui.add_space(8.0);
ui.allocate_ui_with_layout(
egui::vec2(120.0, 20.0),
egui::Layout::left_to_right(egui::Align::Center),
|ui| {
if dashboard
.pending
.as_ref()
.is_some_and(|(ask, _)| *ask == Ask::View)
{
ui.spinner();
ui.label(egui::RichText::new("Updating").small());
} else if let Some((note, _)) = &dashboard.note {
ui.add(egui::Label::new(egui::RichText::new(note).small()).truncate());
}
},
);
});
ui.add_space(6.0);
});
} }
/// Ask before zeroing: it can't be undone. /// Ask before zeroing: it can't be undone.
fn zero_question(dashboard: &mut Dashboard, ctx: &egui::Context) { fn zero_question(dashboard: &mut Dashboard, ctx: &egui::Context) {
let modal = egui::Modal::new(egui::Id::unique("zero-stats-question")).show(ctx, |ui| { let modal = egui::Modal::new(egui::Id::unique("zero-stats-question")).show(ctx, |ui| {
ui.set_max_width(360.0); ui.set_max_width(360.0);
ui.label(egui::RichText::new("Zero sccache's stats?").strong()); ui.add(egui::Label::new(theme::strong("Zero sccache's stats?")).wrap());
ui.add(egui::Label::new( 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 \ "The counters go back to zero. The saved history stays, so the charts keep their \
older data. This can't be undone.", older data. This can't be undone.",
).wrap()); ))
.wrap());
ui.add_space(theme::space::PANEL_GAP);
ui.horizontal(|ui| { ui.horizontal(|ui| {
if ui.button("Zero stats").clicked() { if ui.button("Zero stats").clicked() {
Some(true) Some(true)
@@ -363,7 +464,7 @@ fn zero_question(dashboard: &mut Dashboard, ctx: &egui::Context) {
/// What the page says while no view has arrived yet. /// What the page says while no view has arrived yet.
fn waiting(ui: &mut egui::Ui, error: Option<&str>, refresh_secs: u64) { fn waiting(ui: &mut egui::Ui, error: Option<&str>, refresh_secs: u64) {
let [_, _, bad] = style::marks(ui.visuals().dark_mode); let p = theme::ui(ui);
let retry = if refresh_secs > 0 { let retry = if refresh_secs > 0 {
format!("Trying again every {refresh_secs} seconds.") format!("Trying again every {refresh_secs} seconds.")
} else { } else {
@@ -375,94 +476,259 @@ fn waiting(ui: &mut egui::Ui, error: Option<&str>, refresh_secs: u64) {
format!( format!(
"{error}.\n\nCheck that sccache-dash is running on this machine. {retry}" "{error}.\n\nCheck that sccache-dash is running on this machine. {retry}"
), ),
bad, p.bad,
), ),
None => ( None => (
"Waiting for the first figures".to_owned(), "Waiting for the first figures".to_owned(),
"Asking the server for your cache numbers.".to_owned(), "Asking the server for your cache numbers.".to_owned(),
ui.visuals().text_color(), p.text,
), ),
}; };
// The same height the headline and cards take, so the page doesn't jump when they arrive. // The same height the headline and cards take, so the page doesn't jump when they arrive.
ui.allocate_ui_with_layout( let width = ui.available_rect_before_wrap().width();
egui::vec2(ui.available_rect_before_wrap().width(), 250.0), let height = theme::layout::HEADLINE_HEIGHT + theme::space::PANEL_GAP + theme::layout::STRIP_ROW_HEIGHT * 2.0;
egui::Layout::centered_and_justified(egui::Direction::TopDown), let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
|ui| { let mut place = ui.new_child(
ui.vertical(|ui| { egui::UiBuilder::new()
ui.label(egui::RichText::new(heading).size(20.0).color(color)); .max_rect(rect)
ui.add(egui::Label::new(body).wrap()); .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());
});
} }
/// The whole page below the controls. /// A notice that the server can't be reached, shown over the page rather than
fn page( /// in it, so what is already on screen keeps its place and height.
ui: &mut egui::Ui, fn lost_contact(ctx: &egui::Context, error: &str, from: i64, page_width: f32) {
view: &View, let p = theme::ctx(ctx);
asked: Range, let when = fmt::moment_text(from + fmt::local_offset());
error: Option<&str>, egui::Area::new(egui::Id::unique("lost-contact"))
hidden_languages: &mut Vec<String>, .anchor(
) { egui::Align2::RIGHT_TOP,
let dark = ui.visuals().dark_mode; egui::vec2(-theme::space::PAGE_MARGIN, theme::layout::TOOLBAR_HEIGHT + 3.0 * theme::space::PAGE_MARGIN),
let [_, _, bad] = style::marks(dark); )
if let Some(error) = error { .order(egui::Order::Foreground)
let from = fmt::moment_text(view.generated_at + fmt::local_offset()); .show(ctx, |ui| {
style::banner( let width = (page_width - 2.0 * theme::space::PAGE_MARGIN).min(440.0);
ui, egui::Frame::NONE
format!("Lost contact with the server: {error}. These figures are from {from}."), .fill(p.panel)
bad, .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 { if let Some(error) = &view.server.error {
style::banner(ui, format!("sccache is not working: {error}"), bad); 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);
} }
headline(ui, view, asked, dark);
ui.add_space(10.0);
cards::row(ui, view, dark);
problems::section(ui, view, dark);
where_went::section(ui, view, dark);
overtime::section(ui, view, hidden_languages, dark);
speed::section(ui, view);
extras::section(ui, view);
raw::section(ui, view);
ui.add_space(12.0);
} }
/// One of the three big figures. /// One of the three big figures.
struct Figure<'a> { struct Figure<'a> {
value: String, value: String,
/// The size of the figure's text: a number, or words at the card size.
size: f32,
color: egui::Color32, color: egui::Color32,
caption: String, caption: String,
/// Smaller print under the figure. /// Smaller print under the figure.
small: String, small: String,
/// A second line of smaller print, kept so the block's height never changes. /// A second line of smaller print; the block keeps its height when it is empty.
small2: String, small2: String,
/// A trend line and the value it is drawn against. /// A trend line and the value it is drawn against.
trend: Option<(&'a [Option<f64>], f64)>, trend: Option<(&'a [Option<f64>], f64)>,
/// Instead of a trend line and small print: the problems list.
problems: Option<&'a View>,
hover: Option<String>, 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<'_> { impl Figure<'_> {
/// Draw in a column `width` wide and always the same height. /// Draw in a column `width` wide and always the same height.
fn draw(self, ui: &mut egui::Ui, width: f32) { fn draw(self, ui: &mut egui::Ui, width: f32) {
let gap = ui.spacing().item_spacing.y; let gap = theme::space::LINE;
let block = ui.allocate_ui_with_layout( let block = ui.allocate_ui_with_layout(
egui::vec2(width, FIGURE_HEIGHT), egui::vec2(width, theme::layout::FIGURE_HEIGHT),
egui::Layout::top_down(egui::Align::Min), egui::Layout::top_down(egui::Align::Min),
|ui| { |ui| {
ui.set_width(width); ui.set_width(width);
ui.add( ui.spacing_mut().item_spacing = egui::vec2(gap, gap);
egui::Label::new(egui::RichText::new(&self.value).size(30.0).color(self.color)) // Shrink a long figure to the column instead of cutting it.
.truncate(), 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(egui::RichText::new(&self.caption).small()).truncate()); ui.add(egui::Label::new(theme::title(ui, self.caption.clone())).truncate());
match self.trend { ui.add_space(gap * 2.0);
Some((values, top)) => style::sparkline(ui, TREND_HEIGHT, values, top, self.color), if let Some(view) = self.problems {
None => ui.add_space(TREND_HEIGHT + gap), let room = ui.available_height();
problems::hero_list(ui, view, room);
return;
} }
ui.add(egui::Label::new(egui::RichText::new(&self.small).small().weak()).truncate()); match self.trend {
ui.add(egui::Label::new(egui::RichText::new(&self.small2).small().weak()).truncate()); 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 { if let Some(hover) = self.hover {
@@ -471,14 +737,11 @@ impl Figure<'_> {
} }
} }
const TREND_HEIGHT: f32 = 22.0;
const FIGURE_HEIGHT: f32 = 120.0;
/// The big numbers, what they mean, and where the cache lives. /// The big numbers, what they mean, and where the cache lives.
fn headline(ui: &mut egui::Ui, view: &View, asked: Range, dark: bool) { fn headline(ui: &mut egui::Ui, view: &View, asked: Range) {
let range = view.range.unwrap_or(asked); let range = view.range.unwrap_or(asked);
let totals = &view.totals; let totals = &view.totals;
let text_color = ui.visuals().text_color(); let p = theme::ui(ui);
let rates: Vec<Option<f64>> = view let rates: Vec<Option<f64>> = view
.buckets .buckets
@@ -493,114 +756,181 @@ fn headline(ui: &mut egui::Ui, view: &View, asked: Range, dark: bool) {
let saved_top = saved.iter().flatten().fold(0.0_f64, |top, seconds| top.max(*seconds)); let saved_top = saved.iter().flatten().fold(0.0_f64, |top, seconds| top.max(*seconds));
let problems = view.problems.len(); let problems = view.problems.len();
let worst = view.problems.first();
let problem_color = match worst.map(|problem| problem.severity) {
Some(sccache_dash_api::Severity::Error) => style::marks(dark)[2],
Some(sccache_dash_api::Severity::Warning) => style::marks(dark)[1],
None => text_color,
};
ui.label(egui::RichText::new(range.label().to_uppercase()).strong()); let counts = format!(
let width = ui.available_rect_before_wrap().width();
let spacing = ui.spacing().item_spacing.x;
// Side by side where there is room; one under another on a phone.
let columns = if width >= 600.0 { 3.0 } else { 1.0 };
let column = (width - spacing * (columns - 1.0)) / columns;
ui.horizontal_wrapped(|ui| {
Figure {
value: fmt::percent(totals.hit_rate()),
color: style::hit_rate_color(totals.hit_rate(), dark),
caption: "from cache".into(),
small: format!("{} of all compiler calls", fmt::percent(totals.hit_rate_of_all())),
trend: Some((&rates, 1.0)),
hover: None,
small2: String::new(),
}
.draw(ui, column);
let left_out = view.time_saved.hits_left_out;
// The 90% range goes first; the hits left out are the line under it.
let interval = view
.time_saved
.interval_90
.map(|(low, high)| format!("{} – {} (90% range)", fmt::duration(low), fmt::duration(high)));
Figure {
value: format!("~{}", fmt::duration(view.time_saved.seconds)),
color: text_color,
caption: "saved (rough)".into(),
small: interval.unwrap_or_default(),
small2: if left_out > 0 {
format!("{} hits left out of this figure", fmt::count(left_out))
} else {
"every hit counted".into()
},
trend: Some((&saved, saved_top)),
hover: Some(view.time_saved.note.clone()),
}
.draw(ui, column);
Figure {
value: if problems == 1 {
"1 problem".into()
} else if problems == 0 {
"No problems".into()
} else {
format!("{} problems", fmt::count(problems as u64))
},
color: problem_color,
caption: worst
.map(|problem| problem.title.clone())
.unwrap_or_else(|| "Nothing needs attention".into()),
small: String::new(),
small2: String::new(),
trend: None,
hover: None,
}
.draw(ui, column);
});
// Timeouts, cache errors and forced recaches are inside the built count, as sccache counts them.
let built = totals.misses;
ui.add(egui::Label::new(format!(
"{} compiles · {} from cache · {} built", "{} compiles · {} from cache · {} built",
fmt::count(totals.requests), fmt::count(totals.requests),
fmt::count(totals.hits), fmt::count(totals.hits),
fmt::count(built) fmt::count(totals.misses)
)).wrap());
let server = &view.server;
let mut parts = Vec::new();
if let Some(location) = &server.cache_location {
// sccache words it `Local disk: "/home/me/.cache/sccache"`; the kind is enough here.
let kind = location.split(':').next().unwrap_or(location);
let kind = if kind.eq_ignore_ascii_case("LOCAL DISK") {
"local disk".to_owned()
} else {
kind.to_owned()
};
parts.push(kind);
}
if let (Some(size), Some(max)) = (server.cache_size, server.max_cache_size) {
parts.push(format!("{} of {}", fmt::bytes(size), fmt::bytes(max)));
}
if let Some(version) = server.version.as_deref().or(server.client_version.as_deref()) {
parts.push(format!("sccache {version}"));
}
parts.push(
match server.status {
sccache_dash_api::Status::Running => "running",
sccache_dash_api::Status::Idle => "idle",
sccache_dash_api::Status::NotRunning => "not running",
}
.to_owned(),
); );
let line = format!("Cache: {}", parts.join(" · ")); let title_text = theme::title(ui, range.label()).text().to_owned();
let response = ui.add(egui::Label::new(line).wrap()); let counts_text = counts.clone();
if let Some(location) = &server.cache_location { let width = ui.available_rect_before_wrap().width();
response.on_hover_text(location.clone()); // Side by side where there is room; one under another on a phone.
} let side_by_side = width >= 600.0;
if let (Some(size), Some(max)) = (server.cache_size, server.max_cache_size) { let spacing = theme::space::PANEL_GAP;
let full = if max > 0 { size as f64 / max as f64 } else { 0.0 }; let height = if side_by_side {
let color = if full >= 0.95 { style::marks(dark)[2] } else { style::CACHE }; theme::layout::HEADLINE_HEIGHT
style::meter(ui, 6.0, full, color); } 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);
} }
+51 -58
View File
@@ -1,19 +1,20 @@
//! The six compact cards under the headline. //! 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 eframe::egui::{self, Color32, RichText, Ui};
use sccache_dash_api::{Range, View}; use sccache_dash_api::{Range, View};
use crate::fmt; use crate::fmt;
use crate::style; use crate::style;
use crate::theme;
/// Every card is this tall, whatever it has to say. /// The cards in `per_row` per row: six in one row on a wide screen, three in
const HEIGHT: f32 = 78.0; /// the two-column layout, two on a phone.
pub fn row(ui: &mut egui::Ui, view: &View, per_row: usize) {
pub fn row(ui: &mut Ui, view: &View, dark: bool) {
let totals = &view.totals; let totals = &view.totals;
let previous = view.previous.as_ref(); let previous = view.previous.as_ref();
let range = view.range.unwrap_or(Range::Day); let range = view.range.unwrap_or(Range::Day);
let [good, _, bad] = style::marks(dark); let p = theme::ui(ui);
let requests = totals.requests; let requests = totals.requests;
let cache_errors = totals.errors(); let cache_errors = totals.errors();
let cards = [ let cards = [
@@ -36,7 +37,7 @@ pub fn row(ui: &mut Ui, view: &View, dark: bool) {
Card { Card {
title: "Timeouts", title: "Timeouts",
count: totals.timeouts, count: totals.timeouts,
color: (totals.timeouts > 0).then_some(bad), color: (totals.timeouts > 0).then_some(p.bad),
detail: String::new(), detail: String::new(),
previous: previous.map(|previous| previous.timeouts), previous: previous.map(|previous| previous.timeouts),
good_when_up: false, good_when_up: false,
@@ -44,7 +45,7 @@ pub fn row(ui: &mut Ui, view: &View, dark: bool) {
Card { Card {
title: "Cache errors", title: "Cache errors",
count: cache_errors, count: cache_errors,
color: (cache_errors > 0).then_some(bad), color: (cache_errors > 0).then_some(p.bad),
detail: format!( detail: format!(
"{} read · {} write · {} other", "{} read · {} write · {} other",
fmt::count(totals.read_errors), fmt::count(totals.read_errors),
@@ -72,16 +73,36 @@ pub fn row(ui: &mut Ui, view: &View, dark: bool) {
}, },
]; ];
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 width = ui.available_rect_before_wrap().width();
let spacing = ui.spacing().item_spacing.x; let cell_width = width / per_row as f32;
// Three across where there is room, two on a phone. let height = theme::layout::STRIP_ROW_HEIGHT;
let per_row = if width >= 700.0 { 3.0 } else { 2.0 }; let rule = egui::Stroke::new(1.0, p.border);
let card_width = (width - spacing * (per_row - 1.0)) / per_row; ui.painter().hline(left..=left + width, top + 0.5, rule);
ui.horizontal_wrapped(|ui| { for (line_index, line) in cards.chunks(per_row).enumerate() {
for card in cards { if line_index > 0 {
card.draw(ui, card_width, range, [good, bad]); 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 { struct Card {
@@ -97,54 +118,26 @@ struct Card {
good_when_up: bool, good_when_up: bool,
} }
impl Card {
fn draw(self, ui: &mut Ui, width: f32, range: Range, [good, bad]: [Color32; 2]) {
let margin = 8.0;
// Laid out from the top down inside exactly `width`, whatever row it sits in.
ui.allocate_ui_with_layout(egui::vec2(width, HEIGHT), egui::Layout::top_down(egui::Align::Min), |ui| {
egui::Frame::group(ui.style())
.inner_margin(margin)
.show(ui, |ui| {
ui.set_width(ui.available_rect_before_wrap().width() - 2.0);
ui.set_min_height(HEIGHT - 2.0 * margin);
ui.add(egui::Label::new(RichText::new(self.title).small()).truncate());
let color = self.color.unwrap_or_else(|| ui.visuals().text_color());
ui.add(egui::Label::new(RichText::new(fmt::count(self.count)).size(20.0).color(color)).truncate());
let detail = ui.add(
egui::Label::new(RichText::new(&self.detail).small().weak()).truncate(),
);
if !self.detail.is_empty() {
detail.on_hover_text(self.detail.clone());
}
let (change, color) = change(self.count, self.previous, range, self.good_when_up, [good, bad]);
ui.add(egui::Label::new(RichText::new(change).small().color(color)).truncate());
});
});
}
}
/// How a count compares with the period before, and the colour that change deserves. /// How a count compares with the period before, and the colour that change deserves.
fn change( fn change(count: u64, previous: Option<u64>, range: Range, good_when_up: bool, p: &theme::Palette) -> RichText {
count: u64,
previous: Option<u64>,
range: Range,
good_when_up: bool,
[good, bad]: [Color32; 2],
) -> (String, Color32) {
let gray = Color32::GRAY;
let Some(previous) = previous else { let Some(previous) = previous else {
return (String::new(), gray); return RichText::new("").font(egui::FontId::proportional(theme::px::SMALL));
}; };
if previous == 0 { if previous == 0 {
return (if count == 0 { String::new() } else { "was 0 before".into() }, gray); 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; let change = (count as f64 - previous as f64) / previous as f64 * 100.0;
if change.abs() < 0.5 { if change.abs() < 0.5 {
return ("no change".into(), gray); return small_plain(p, "no change".into());
} }
let better = (change > 0.0) == good_when_up; let better = (change > 0.0) == good_when_up;
( RichText::new(format!("{change:+.0}% vs {}", fmt::previous_label(range)))
format!("{change:+.0}% vs {}", fmt::previous_label(range)), .font(egui::FontId::proportional(theme::px::SMALL))
if better { good } else { bad }, .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));
}
}
+16 -28
View File
@@ -1,34 +1,22 @@
//! Extras: the tables sccache only fills in for some setups. //! Extras: the tables sccache only fills in for some setups, one panel each.
use eframe::egui::{RichText, Ui};
use sccache_dash_api::View; use sccache_dash_api::View;
use crate::style; use crate::style::{self, Cell};
use crate::theme;
pub fn section(ui: &mut Ui, view: &View) { pub fn section(ui: &mut eframe::egui::Ui, view: &View) {
if view.extras.is_empty() { for extra in &view.extras {
return; 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);
} }
style::section(ui, "extras", "Extras", |ui| {
for (index, extra) in view.extras.iter().enumerate() {
if index > 0 {
ui.add_space(6.0);
}
ui.label(RichText::new(&extra.title).strong());
let label_width = if ui.available_rect_before_wrap().width() < 480.0 {
104.0
} else {
160.0
};
for (label, value) in &extra.rows {
style::table_row(
ui,
vec![
style::text_cell(RichText::new(label.as_str()).strong(), label_width, false, false),
style::text_cell(RichText::new(value.as_str()), f32::INFINITY, false, true),
],
);
}
}
});
} }
+33
View File
@@ -9,6 +9,13 @@ pub fn previous_label(range: Range) -> String {
format!("previous {}", label.strip_prefix("last ").unwrap_or(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 /// 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. /// leftovers of rounding to the largest shares. All zero when nothing is counted.
pub fn shares(parts: &[u64]) -> Vec<u64> { pub fn shares(parts: &[u64]) -> Vec<u64> {
@@ -215,10 +222,29 @@ pub fn tick_label(unix: i64, step: i64) -> String {
} }
} }
/// 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)] #[cfg(test)]
mod tests { mod tests {
use super::*; 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] #[test]
fn counts_have_thousands_separators() { fn counts_have_thousands_separators() {
assert_eq!(count(0), "0"); assert_eq!(count(0), "0");
@@ -277,4 +303,11 @@ mod tests {
let parts = [3254, 3256, 829, 14, 13]; let parts = [3254, 3256, 829, 14, 13];
assert_eq!(shares(&parts).iter().sum::<u64>(), 100); 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++"]);
}
} }
+6 -2
View File
@@ -1,6 +1,7 @@
//! The sccache-dash dashboard page. `trunk` compiles this to WebAssembly and //! The sccache-dash dashboard page. `trunk` compiles this to WebAssembly and
//! the sccache-dash server serves it at http://127.0.0.1:8226. //! the sccache-dash server serves it at http://127.0.0.1:8226.
pub mod disclosure;
pub mod fmt; pub mod fmt;
// Drawing needs eframe, which is only built for the browser so far; the rest // Drawing needs eframe, which is only built for the browser so far; the rest
@@ -24,6 +25,8 @@ mod speed;
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]
mod style; mod style;
#[cfg(target_arch = "wasm32")] #[cfg(target_arch = "wasm32")]
mod theme;
#[cfg(target_arch = "wasm32")]
mod where_went; mod where_went;
/// The canvas in `index.html` the page is drawn on. /// The canvas in `index.html` the page is drawn on.
@@ -112,7 +115,7 @@ mod tests {
{ "name": "Rust", "hits": 229, "misses": 3256, "errors": 0 }, { "name": "Rust", "hits": 229, "misses": 3256, "errors": 0 },
{ "name": "C/C++", "hits": 2082, "misses": 0, "errors": 0 } { "name": "C/C++", "hits": 2082, "misses": 0, "errors": 0 }
], ],
"not_cached": [["crate-type", 621], ["incremental", 105]], "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": [ "buckets": [
{ "start": 1764290000, "hits": 10, "misses": 5, "other": 1, "errors": 0, "saved_seconds": 60.0, { "start": 1764290000, "hits": 10, "misses": 5, "other": 1, "errors": 0, "saved_seconds": 60.0,
"languages": [["Rust", 10, 5]], "reset": false, "gap": false }, "languages": [["Rust", 10, 5]], "reset": false, "gap": false },
@@ -138,7 +141,8 @@ mod tests {
assert_eq!(view.time_saved.interval_90, Some((9700.0, 12600.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[0].bins[1].compiles, 980);
assert_eq!(view.build_times[1].compiles, 0); assert_eq!(view.build_times[1].compiles, 0);
assert_eq!(view.not_cached[0], ("crate-type".to_owned(), 621)); 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.buckets[1].gap, true);
assert_eq!(view.extras[0].rows[0].1, "2"); assert_eq!(view.extras[0].rows[0].1, "2");
} }
+185 -118
View File
@@ -1,74 +1,57 @@
//! Over time: hit rate and compile volume per bucket, with a language filter. //! 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, Color32, RichText, Stroke, Ui}; use eframe::egui::{self, Stroke, Ui};
use egui_plot::{ use egui_plot::{
Bar, BarChart, CoordinatesFormatter, Corner, GridInput, GridMark, Legend, Line, LineStyle, Bar, BarChart, CoordinatesFormatter, Corner, GridInput, GridMark, Line, LineStyle, Plot,
Plot, PlotBounds, PlotPoint, PlotPoints, PlotResponse, PlotUi, Span, VLine, PlotBounds, PlotPoint, PlotPoints, PlotResponse, PlotUi, Span, VLine,
}; };
use sccache_dash_api::{Bucket, Range, View}; use sccache_dash_api::{Bucket, Range, View};
use crate::fmt; use crate::fmt;
use crate::style; use crate::style;
use crate::theme;
const CHART_HEIGHT: f32 = 170.0;
/// Hits out of the cacheable compiles; `None` when there were none. /// Hits out of the cacheable compiles; `None` when there were none.
pub fn hit_rate(hits: u64, misses: u64) -> Option<f64> { pub fn hit_rate(hits: u64, misses: u64) -> Option<f64> {
(hits + misses > 0).then(|| hits as f64 / (hits + misses) as f64) (hits + misses > 0).then(|| hits as f64 / (hits + misses) as f64)
} }
pub fn section(ui: &mut Ui, view: &View, hidden: &mut Vec<String>, dark: bool) { fn axes_of(view: &View, dark: bool) -> Axes {
style::section(ui, "overtime", "Over time", |ui| { let step = bucket_step(&view.buckets, view.range);
filter(ui, view, hidden); Axes {
window: range_window(view, step),
let tz = fmt::local_offset(); step,
let step = bucket_step(&view.buckets, view.range); tz: fmt::local_offset() as f64,
let window = view dark,
.buckets }
.iter()
.filter(|bucket| !bucket.gap)
.map(|bucket| (bucket.start + tz) as f64)
.fold(None::<(f64, f64)>, |window, start| {
Some(match window {
Some((first, last)) => (first.min(start), last.max(start)),
None => (start, start),
})
});
let axes = Axes { window, step, tz };
ui.label(RichText::new("Hit rate").strong());
hit_rate_chart(ui, view, hidden, axes, dark);
ui.add_space(6.0);
ui.label(RichText::new("Compiles").strong());
volume_chart(ui, view, hidden, axes, dark);
});
} }
/// What both charts share: the time window, the bucket width and the time zone. /// The body of the "Hit rate over time" panel.
#[derive(Clone, Copy)] pub fn hit_rate_panel(ui: &mut Ui, view: &View, hidden: &[String], chart_height: f32) {
struct Axes { let axes = axes_of(view, theme::ui(ui).dark);
/// First and last bucket start shown, if any bucket was recorded. hit_rate_chart(ui, view, hidden, axes, chart_height);
window: Option<(f64, f64)>, }
/// Seconds per bucket.
step: f64, /// The body of the "Compiles over time" panel.
/// Seconds to add to a Unix time to get local clock time. pub fn volume_panel(ui: &mut Ui, view: &View, hidden: &[String], chart_height: f32) {
tz: i64, 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. /// Checkboxes that narrow both charts to some languages.
fn filter(ui: &mut Ui, view: &View, hidden: &mut Vec<String>) { pub fn filter(ui: &mut Ui, view: &View, hidden: &mut Vec<String>) {
ui.horizontal_wrapped(|ui| { ui.horizontal_wrapped(|ui| {
ui.spacing_mut().item_spacing.x = theme::space::PANEL_GAP;
let mut all = hidden.is_empty(); let mut all = hidden.is_empty();
if ui.checkbox(&mut all, "All languages").changed() { if ui.checkbox(&mut all, "All languages").changed() {
*hidden = if all { *hidden = fmt::hidden_after_all(all, view.languages.iter().map(|l| l.name.as_str()));
view.languages
.iter()
.map(|language| language.name.clone())
.collect()
} else {
Vec::new()
};
} }
for language in &view.languages { for language in &view.languages {
let mut ticked = !hidden.iter().any(|name| name == &language.name); let mut ticked = !hidden.iter().any(|name| name == &language.name);
@@ -82,13 +65,14 @@ fn filter(ui: &mut Ui, view: &View, hidden: &mut Vec<String>) {
} }
}); });
if !hidden.is_empty() { if !hidden.is_empty() {
ui.label( ui.add(
RichText::new( egui::Label::new(
"Only the chosen languages are counted. The other outcomes can't be split by \ theme::small(
language, so they're left out.", ui,
) "Only the chosen languages are counted. The other outcomes can't be split by \
.small() language, so they're left out.",
.weak(), ),
),
); );
} }
} }
@@ -108,35 +92,101 @@ fn bucket_step(buckets: &[Bucket], range: Option<Range>) -> f64 {
} }
} }
/// A chart with a time axis: clock times as ticks and a readout of where the /// The whole selected range as Unix seconds (start, end): a fixed-length range
/// pointer is. It can't be zoomed or dragged, so the wheel and a finger keep /// runs back from now by its length, whatever the buckets cover; "since reset"
/// scrolling the page; that also means it can fit its data afresh every frame, /// runs from the first bucket to the last one's end.
/// so new buckets are never cut off. 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>( fn time_plot<'a>(
name: &'static str, name: &'static str,
axes: Axes, axes: Axes,
height: f32,
readout: impl Fn(&PlotPoint) -> String + 'a, readout: impl Fn(&PlotPoint) -> String + 'a,
) -> Plot<'a> { ) -> Plot<'a> {
let (first, last) = axes.window.unwrap_or((0.0, axes.step)); let (first, last) = (axes.window.0 + axes.tz, axes.window.1 + axes.tz);
let step = axes.step; let span = last - first;
let tick = fmt::tick_step(last - first + 2.0 * step); let air = span * theme::drawing::CHART_SIDE_AIR;
let plot = Plot::new(name) let tick = fmt::tick_step(span);
.height(CHART_HEIGHT) 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_scroll(false)
.allow_drag(false) .allow_drag(false)
.allow_zoom(false) .allow_zoom(false)
.allow_boxed_zoom(false) .allow_boxed_zoom(false)
.include_x(first - step) .custom_x_axes(vec![egui_plot::AxisHints::new_x()
.include_x(last + step) .tick_label_font(label_font.clone())
.x_grid_spacer(move |input: GridInput| ticks(input.bounds.0, input.bounds.1, tick)) .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| { .x_axis_formatter(move |mark: GridMark, _range| {
fmt::tick_label(mark.value.round() as i64, tick) fmt::tick_label(mark.value.round() as i64, tick)
}) })
.coordinates_formatter( .coordinates_formatter(
Corner::LeftTop, Corner::LeftTop,
CoordinatesFormatter::new(move |point: &PlotPoint, _bounds: &PlotBounds| readout(point)), CoordinatesFormatter::new(move |point: &PlotPoint, _bounds: &PlotBounds| readout(point)),
); )
plot.reset() .reset()
} }
fn ticks(from: f64, to: f64, tick: i64) -> Vec<GridMark> { fn ticks(from: f64, to: f64, tick: i64) -> Vec<GridMark> {
@@ -154,31 +204,32 @@ fn ticks(from: f64, to: f64, tick: i64) -> Vec<GridMark> {
marks marks
} }
/// Resets as dashed lines and gaps as grey bands, so a gap never reads as zero. /// Resets as dashed lines, and everything unrecorded as one tinted band per stretch.
fn marks(plot: &mut PlotUi<'_>, buckets: &[Bucket], step: f64, dark: bool, tz: i64) { fn marks(plot: &mut PlotUi<'_>, buckets: &[Bucket], axes: Axes) {
let warn = style::marks(dark)[1]; let p = theme::of(axes.dark);
let shade = if dark {
Color32::WHITE.gamma_multiply(0.08)
} else {
Color32::BLACK.gamma_multiply(0.08)
};
for bucket in buckets { for bucket in buckets {
let start = (bucket.start + tz) as f64;
if bucket.reset { if bucket.reset {
plot.vline( plot.vline(
VLine::new("Reset", start) VLine::new("Reset", bucket.start as f64 + axes.tz)
.stroke(Stroke::new(1.5, warn)) .stroke(Stroke::new(1.5, p.warn))
.style(LineStyle::Dashed { length: 12.0 }), .style(LineStyle::Dashed { length: 12.0 }),
); );
} }
if bucket.gap {
plot.span(
Span::new("Not recorded", start..=start + step)
.fill(shade)
.border_width(0.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) { fn overlay(ui: &mut Ui, chart: &PlotResponse<()>, text: &str) {
@@ -186,8 +237,8 @@ fn overlay(ui: &mut Ui, chart: &PlotResponse<()>, text: &str) {
chart.response.rect.center(), chart.response.rect.center(),
egui::Align2::CENTER_CENTER, egui::Align2::CENTER_CENTER,
text, text,
egui::TextStyle::Body.resolve(ui.style()), egui::FontId::proportional(theme::px::SMALL),
ui.visuals().weak_text_color(), theme::ui(ui).muted,
); );
} }
@@ -206,21 +257,18 @@ fn split(bucket: &Bucket, hidden: &[String]) -> (u64, u64) {
} }
} }
fn hit_rate_chart( fn hit_rate_chart(ui: &mut Ui, view: &View, hidden: &[String], axes: Axes, height: f32) {
ui: &mut Ui, let p = theme::ui(ui);
view: &View,
hidden: &[String],
axes: Axes,
dark: bool,
) {
let (step, tz) = (axes.step, axes.tz);
// One line per stretch of buckets that have a hit rate. // One line per stretch of buckets that have a hit rate.
let mut runs: Vec<Vec<PlotPoint>> = Vec::new(); let mut runs: Vec<Vec<PlotPoint>> = Vec::new();
let mut run: Vec<PlotPoint> = Vec::new(); let mut run: Vec<PlotPoint> = Vec::new();
for bucket in view.buckets.iter().filter(|bucket| !bucket.gap) { for bucket in view.buckets.iter().filter(|bucket| !bucket.gap) {
let (hits, misses) = split(bucket, hidden); let (hits, misses) = split(bucket, hidden);
match hit_rate(hits, misses) { match hit_rate(hits, misses) {
Some(rate) => run.push(PlotPoint::new((bucket.start + tz) as f64, rate * 100.0)), 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(std::mem::take(&mut run)),
None => {} None => {}
} }
@@ -232,6 +280,7 @@ fn hit_rate_chart(
let plot = time_plot( let plot = time_plot(
"hit-rate-chart", "hit-rate-chart",
axes, axes,
height,
|point| format!("{} · {:.0}%", fmt::moment_text(point.x.round() as i64), point.y), |point| format!("{} · {:.0}%", fmt::moment_text(point.x.round() as i64), point.y),
) )
.default_y_bounds(0.0, 100.0) .default_y_bounds(0.0, 100.0)
@@ -246,11 +295,11 @@ fn hit_rate_chart(
}) })
.y_axis_formatter(|mark: GridMark, _| format!("{:.0}%", mark.value)); .y_axis_formatter(|mark: GridMark, _| format!("{:.0}%", mark.value));
let chart = plot.show(ui, |plot| { let chart = plot.show(ui, |plot| {
marks(plot, &view.buckets, step, dark, tz); marks(plot, &view.buckets, axes);
for points in &runs { for points in &runs {
plot.line( plot.line(
Line::new("Hit rate", PlotPoints::Owned(points.clone())) Line::new("Hit rate", PlotPoints::Owned(points.clone()))
.color(style::CACHE) .color(p.from_cache)
.width(2.0), .width(2.0),
); );
} }
@@ -258,16 +307,19 @@ fn hit_rate_chart(
if runs.is_empty() { if runs.is_empty() {
overlay(ui, &chart, "No cacheable compiles in this range"); 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( fn volume_chart(ui: &mut Ui, view: &View, hidden: &[String], axes: Axes, height: f32) {
ui: &mut Ui, let p = theme::ui(ui);
view: &View,
hidden: &[String],
axes: Axes,
dark: bool,
) {
let (step, tz) = (axes.step, axes.tz);
// The tallest stack of one bucket, with a little air above it. // The tallest stack of one bucket, with a little air above it.
let top = view let top = view
.buckets .buckets
@@ -281,17 +333,17 @@ fn volume_chart(
let plot = time_plot( let plot = time_plot(
"volume-chart", "volume-chart",
axes, axes,
height,
|point| fmt::moment_text(point.x.round() as i64), |point| fmt::moment_text(point.x.round() as i64),
) )
.legend(Legend::default().position(Corner::RightTop))
.default_y_bounds(0.0, top) .default_y_bounds(0.0, top)
.y_axis_formatter(|mark: GridMark, _| fmt::count(mark.value.max(0.0).round() as u64)); .y_axis_formatter(|mark: GridMark, _| fmt::count(mark.value.max(0.0).round() as u64));
let width = step * 0.8; let width = axes.step * 0.8;
let (mut from_cache, mut built, mut other) = (vec![], vec![], vec![]); let (mut from_cache, mut built, mut other) = (vec![], vec![], vec![]);
let mut any = false; let mut any = false;
for bucket in view.buckets.iter().filter(|bucket| !bucket.gap) { for bucket in view.buckets.iter().filter(|bucket| !bucket.gap) {
let x = (bucket.start + tz) as f64; let x = bucket.start as f64 + axes.tz;
let (hits, misses) = split(bucket, hidden); let (hits, misses) = split(bucket, hidden);
for (bars, count) in [ for (bars, count) in [
(&mut from_cache, hits), (&mut from_cache, hits),
@@ -306,18 +358,18 @@ fn volume_chart(
} }
let chart = plot.show(ui, |plot| { let chart = plot.show(ui, |plot| {
marks(plot, &view.buckets, step, dark, tz); marks(plot, &view.buckets, axes);
let from_cache = BarChart::new("From cache", from_cache) let from_cache = BarChart::new("From cache", from_cache)
.width(width) .width(width)
.color(style::CACHE); .color(p.from_cache);
let built = BarChart::new("Built", built) let built = BarChart::new("Built", built)
.width(width) .width(width)
.color(style::BUILT) .color(p.built);
.stack_on(&[&from_cache]);
let other = BarChart::new("Not cacheable and other", other) let other = BarChart::new("Not cacheable and other", other)
.width(width) .width(width)
.color(style::NOT_CACHEABLE) .color(p.not_cacheable);
.stack_on(&[&built]); let built = built.stack_on(&[&from_cache]);
let other = other.stack_on(&[&built]);
plot.bar_chart(from_cache); plot.bar_chart(from_cache);
plot.bar_chart(built); plot.bar_chart(built);
if hidden.is_empty() { if hidden.is_empty() {
@@ -327,4 +379,19 @@ fn volume_chart(
if !any { if !any {
overlay(ui, &chart, "Nothing recorded in this range"); 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);
} }
+71 -36
View File
@@ -1,42 +1,77 @@
//! Problems: what is wrong, most serious first. //! 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, RichText, Stroke, Ui}; use eframe::egui::{self, Sense, Ui};
use sccache_dash_api::{Severity, View}; use sccache_dash_api::{Severity, View};
use crate::style; use crate::theme;
use crate::where_went::chevron;
pub fn section(ui: &mut Ui, view: &View, dark: bool) { const ROW: f32 = 22.0;
style::section(ui, "problems", "Problems", |ui| { const GAP: f32 = 8.0;
if view.problems.is_empty() { const CHEVRON: f32 = 8.0;
ui.label("No problems.");
return; fn open_id(title: &str) -> egui::Id {
} egui::Id::new(("problem-open", title))
let [_, warn, bad] = style::marks(dark); }
for problem in &view.problems {
let color = match problem.severity { /// The problems of `view` in a list `height` tall.
Severity::Error => bad, pub fn hero_list(ui: &mut Ui, view: &View, height: f32) {
Severity::Warning => warn, let p = theme::ui(ui);
}; if view.problems.is_empty() {
let kind = match problem.severity { ui.add(egui::Label::new(theme::small(ui, "Nothing needs attention.")).truncate());
Severity::Error => "Error", return;
Severity::Warning => "Warning", }
}; egui::ScrollArea::vertical()
// As wide as there is room, minus a little (see `banner`). .id_salt("hero-problems")
let width = ui.available_rect_before_wrap().width() - 2.0 * 8.0; .max_height(height)
egui::Frame::NONE .auto_shrink([false, false])
.fill(color.gamma_multiply(0.14)) .show(ui, |ui| {
.stroke(Stroke::new(1.0, color)) ui.spacing_mut().item_spacing.y = 0.0;
.corner_radius(6.0) let width = ui.available_width();
.inner_margin(8.0) let indent = theme::drawing::SEVERITY_DOT + GAP;
.show(ui, |ui| { for problem in &view.problems {
ui.set_min_width(width - 6.0); let id = open_id(&problem.title);
ui.horizontal_wrapped(|ui| { let open = ui.ctx().data(|data| data.get_temp::<bool>(id)).unwrap_or(false);
ui.label(RichText::new(kind).small().strong().color(color)); let (row, response) = ui.allocate_exact_size(egui::vec2(width, ROW), Sense::click());
ui.label(RichText::new(&problem.title).strong()); let response = response.on_hover_cursor(egui::CursorIcon::PointingHand);
}); response.widget_info(|| {
ui.add(egui::Label::new(&problem.detail).wrap()); egui::WidgetInfo::labeled(egui::WidgetType::Button, true, problem.title.as_str())
}); });
ui.add_space(4.0); 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);
}
}
});
} }
+137 -39
View File
@@ -1,59 +1,157 @@
//! Raw counters: the sccache stats exactly as the server read them. //! 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 eframe::egui::{self, RichText, Ui}; use std::cell::Cell;
use eframe::egui::{self, Pos2, Rect, Sense, Ui};
use sccache_dash_api::View; use sccache_dash_api::View;
use crate::style; use crate::style;
use crate::theme;
pub fn section(ui: &mut Ui, view: &View) { /// Every leaf of the JSON as its dotted path and its value as text.
style::section(ui, "raw", "Raw counters", |ui| match &view.raw { fn leaves(value: &serde_json::Value, path: String, out: &mut Vec<(String, String)>) {
serde_json::Value::Null => {
ui.label("sccache's raw counters could not be read.");
}
value => tree(ui, value, "raw"),
});
}
/// A tree: one collapsible line per group, `name value` per counter.
fn tree(ui: &mut Ui, value: &serde_json::Value, path: &str) {
match value { match value {
serde_json::Value::Object(fields) => { serde_json::Value::Object(fields) => {
for (name, value) in fields { for (name, value) in fields {
branch(ui, name, value, path); let path = if path.is_empty() { name.clone() } else { format!("{path}.{name}") };
leaves(value, path, out);
} }
} }
serde_json::Value::Array(items) => { serde_json::Value::Array(items) => {
for (index, value) in items.iter().enumerate() { for (index, value) in items.iter().enumerate() {
branch(ui, &index.to_string(), value, path); leaves(value, format!("{path}[{index}]"), out);
} }
} }
leaf => counter(ui, "", leaf), leaf => out.push((
path,
match leaf {
serde_json::Value::String(text) => text.clone(),
serde_json::Value::Null => "null".to_owned(),
number => number.to_string(),
},
)),
} }
} }
fn branch(ui: &mut Ui, name: &str, value: &serde_json::Value, path: &str) { /// How many columns of key/value lines fit in a panel's `inner` width.
let path = format!("{path}/{name}"); fn columns(inner: f32) -> usize {
if value.is_object() || value.is_array() { let gap = theme::space::PANEL_GAP + 4.0;
egui::CollapsingHeader::new(RichText::new(name).strong()) (((inner + gap) / (theme::layout::RAW_LINE_WIDTH + gap)) as usize).clamp(1, 3)
.id_salt(path.clone())
.default_open(true)
.show(ui, |ui| tree(ui, value, &path));
} else {
counter(ui, name, value);
}
} }
/// One counter as sccache prints its value. /// How tall the panel is when it is `width` wide: its title and, when open,
fn counter(ui: &mut Ui, name: &str, value: &serde_json::Value) { /// its lines.
let text = match value { pub fn height(view: &View, width: f32, open: bool) -> f32 {
serde_json::Value::String(text) => text.clone(), let title = theme::space::ROW + theme::space::UNDER_TITLE + 2.0 * theme::space::PANEL_PAD_Y;
serde_json::Value::Null => "null".to_owned(), if !open {
number => number.to_string(), return title - theme::space::UNDER_TITLE + theme::space::LINE;
}; }
ui.horizontal_wrapped(|ui| { let mut lines = 0;
if !name.is_empty() { if !view.raw.is_null() {
ui.label(name); let mut out = Vec::new();
} leaves(&view.raw, String::new(), &mut out);
ui.label(RichText::new(text).weak()); 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}"));
}
}
},
);
}
} }
+111 -108
View File
@@ -1,64 +1,84 @@
//! Speed: how long a cache fetch, a cache write and a build take on average, //! Speed: how long a cache fetch, a cache write and a build take on average,
//! and how build times spread for each language. //! and how build times spread for each language.
use eframe::egui::{self, Color32, Layout, RichText, Sense, Ui}; use eframe::egui::{self, Pos2, Rect, Sense, Ui};
use sccache_dash_api::{BuildTimes, View}; use sccache_dash_api::{BuildTimes, View};
use crate::fmt; use crate::fmt;
use crate::style; use crate::style;
use crate::theme;
/// Every histogram is this tall, whatever it holds.
const HISTOGRAM_HEIGHT: f32 = 44.0;
/// The slowest build time the axis reaches, as log10 of milliseconds (1,000 s). /// The slowest build time the axis reaches, as log10 of milliseconds (1,000 s).
const AXIS_TOP: f64 = 6.0; 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) { pub fn section(ui: &mut Ui, view: &View) {
let p = theme::ui(ui);
let timing = view.timing; let timing = view.timing;
style::section(ui, "speed", "Speed", |ui| { let rows = [
let rows = [ ("Cache fetch (a hit)", timing.avg_hit_read_ms, p.from_cache),
("Cache fetch (a hit)", timing.avg_hit_read_ms, style::CACHE), ("Cache write", timing.avg_cache_write_ms, p.muted),
("Cache write", timing.avg_cache_write_ms, style::BUILT), ("Compile one crate", timing.avg_compile_ms, p.built),
("Build (compile)", timing.avg_compile_ms, Color32::GRAY), ];
]; for (label, ms, color) in rows {
let label_width = if ui.available_rect_before_wrap().width() < 480.0 { ui.horizontal(|ui| {
124.0 ui.spacing_mut().item_spacing.x = theme::space::ITEM;
} else { let (label_rect, _) =
170.0 ui.allocate_exact_size(egui::vec2(LABEL_WIDTH, theme::space::ROW), Sense::hover());
}; let label = style::galley(ui, theme::body(label), false, f32::INFINITY);
for (label, ms, color) in rows { ui.painter().with_clip_rect(label_rect).galley(
ui.horizontal(|ui| { Pos2::new(label_rect.left(), label_rect.center().y - label.size().y / 2.0),
cell(ui, label_width, Layout::left_to_right(egui::Align::Center), |ui| { label,
ui.add(egui::Label::new(label).truncate()); p.text,
}); );
let text = ms.map_or("—".into(), |ms| fmt::duration(ms / 1000.0)); let text = ms.map_or("—".into(), |ms| fmt::duration(ms / 1000.0));
cell(ui, 72.0, Layout::right_to_left(egui::Align::Center), |ui| { let value = style::galley(ui, theme::number(text), false, f32::INFINITY);
ui.label(RichText::new(text).strong()); let value_rect = ui
}); .allocate_exact_size(egui::vec2(VALUE_WIDTH, theme::space::ROW), Sense::hover())
style::meter(ui, 12.0, ms.map_or(0.0, style::log_fraction), color); .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),
let hit = timing.avg_hit_read_ms; value,
let write = timing.avg_cache_write_ms; p.text,
let build = timing.avg_compile_ms; );
let sentence = if let Some(times) = faster(build, hit) { let bar_rect = ui
format!("A cache hit is about {times}x faster than building.") .allocate_exact_size(
} else if let Some(times) = faster(build, write) { egui::vec2(ui.available_rect_before_wrap().width(), theme::space::ROW),
format!("Writing to the cache is about {times}x faster than building.") Sense::hover(),
} else { )
"There are no timings to compare in this range.".to_owned() .0;
}; let bar = Rect::from_center_size(
ui.label(sentence); bar_rect.center(),
ui.label( egui::vec2(bar_rect.width(), theme::drawing::SPEED_BAR),
RichText::new( );
"The bars use a log scale, so a fraction of a millisecond and several \ style::fill_bar(ui, bar, ms.map_or(0.0, style::log_fraction), color);
seconds are both visible.", });
) }
.small() let hit = timing.avg_hit_read_ms;
.weak(), 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); build_times(ui, view);
});
} }
/// `faster` is about how many times shorter than `slower`, when both are known and positive. /// `faster` is about how many times shorter than `slower`, when both are known and positive.
@@ -67,15 +87,10 @@ fn faster(slower: Option<f64>, faster: Option<f64>) -> Option<String> {
(slower > 0.0 && faster > 0.0).then(|| fmt::round_number(slower / faster)) (slower > 0.0 && faster > 0.0).then(|| fmt::round_number(slower / faster))
} }
/// Draw with a fixed width, so the bars all start at the same place. /// "How long one crate takes to compile": one histogram per language, all on the
fn cell(ui: &mut Ui, width: f32, layout: Layout, contents: impl FnOnce(&mut Ui)) {
let height = ui.text_style_height(&egui::TextStyle::Body);
ui.allocate_ui_with_layout(egui::vec2(width, height), layout, contents);
}
/// "How long builds take, by language": one histogram per language, all on the
/// same log scale of build time, with the mean, median and p90 marked. /// same log scale of build time, with the mean, median and p90 marked.
fn build_times(ui: &mut Ui, view: &View) { fn build_times(ui: &mut Ui, view: &View) {
let p = theme::ui(ui);
let languages: Vec<&BuildTimes> = view let languages: Vec<&BuildTimes> = view
.build_times .build_times
.iter() .iter()
@@ -84,8 +99,8 @@ fn build_times(ui: &mut Ui, view: &View) {
if languages.is_empty() { if languages.is_empty() {
return; return;
} }
ui.add_space(8.0); ui.add_space(theme::space::BETWEEN_PARTS);
ui.label(RichText::new("How long builds take, by language").strong()); 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. // 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); let (mut low, mut high) = (f64::MAX, 0.0_f64);
@@ -98,44 +113,33 @@ fn build_times(ui: &mut Ui, view: &View) {
let low = (low.max(1.0).log10() - 0.25).max(0.0); let low = (low.max(1.0).log10() - 0.25).max(0.0);
let high = (high.log10() + 0.25).min(AXIS_TOP); let high = (high.log10() + 0.25).min(AXIS_TOP);
let [_, median_color, p90_color] = style::marks(ui.visuals().dark_mode);
let mean_color = ui.visuals().text_color();
for times in languages { for times in languages {
ui.horizontal_wrapped(|ui| { ui.add_space(theme::space::ITEM);
ui.label(RichText::new(&times.language).strong()); ui.horizontal(|ui| {
ui.label(format!("{} builds", fmt::count(times.compiles))); ui.spacing_mut().item_spacing.x = theme::space::ITEM;
ui.add_space(6.0); ui.add(egui::Label::new(theme::strong(times.language.clone())).truncate());
ui.label(RichText::new(format!("mean {}", ms(times.mean_ms))).small().color(mean_color)); ui.add(egui::Label::new(theme::small(ui, format!("{} compiles", fmt::count(times.compiles)))).truncate());
ui.label( ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
RichText::new(format!("median {}", ms(times.median_ms))) ui.spacing_mut().item_spacing.x = theme::space::ITEM;
.small() for (name, value, color) in [
.color(median_color), ("p90", times.p90_ms, p.p90),
); ("median", times.median_ms, p.median),
ui.label( ("mean", times.mean_ms, p.mean),
RichText::new(format!("p90 {}", ms(times.p90_ms))) ] {
.small() ui.label(theme::small(ui, format!("{name} {}", ms(value))).color(color));
.color(p90_color), }
); });
}); });
histogram( histogram(ui, times, low, high, p);
ui,
times,
low,
high,
[mean_color, median_color, p90_color],
);
axis(ui, low, high); axis(ui, low, high);
ui.add_space(4.0);
} }
ui.add( ui.add(
egui::Label::new( egui::Label::new(
RichText::new( theme::small(
ui,
"Each point is the average of the builds that finished within one 10-second reading.", "Each point is the average of the builds that finished within one 10-second reading.",
) ),
.small() ),
.weak(),
)
.wrap(),
); );
} }
@@ -145,12 +149,14 @@ fn ms(value: f64) -> String {
/// The bins as bars, build time along the bottom on a log scale, with a line /// The bins as bars, build time along the bottom on a log scale, with a line
/// for the mean, median and p90. /// for the mean, median and p90.
fn histogram(ui: &mut Ui, times: &BuildTimes, low: f64, high: f64, colors: [Color32; 3]) { fn histogram(ui: &mut Ui, times: &BuildTimes, low: f64, high: f64, p: &theme::Palette) {
let width = ui.available_rect_before_wrap().width(); let width = ui.available_rect_before_wrap().width();
let (rect, response) = let (rect, response) = ui.allocate_exact_size(
ui.allocate_exact_size(egui::vec2(width, HISTOGRAM_HEIGHT), Sense::hover()); egui::vec2(width, theme::drawing::BUILD_HISTOGRAM),
Sense::hover(),
);
let painter = ui.painter(); let painter = ui.painter();
painter.rect_filled(rect, 3.0, ui.visuals().extreme_bg_color); painter.hline(rect.x_range(), rect.bottom() - 0.5, egui::Stroke::new(1.0, p.grid));
let at = |value: f64| { let at = |value: f64| {
let position = ((value.max(1.0).log10() - low) / (high - low)).clamp(0.0, 1.0); let position = ((value.max(1.0).log10() - low) / (high - low)).clamp(0.0, 1.0);
rect.left() + rect.width() * position as f32 rect.left() + rect.width() * position as f32
@@ -160,17 +166,17 @@ fn histogram(ui: &mut Ui, times: &BuildTimes, low: f64, high: f64, colors: [Colo
if bin.compiles == 0 { if bin.compiles == 0 {
continue; continue;
} }
let height = HISTOGRAM_HEIGHT * bin.compiles as f32 / top.max(1) as f32; let height = theme::drawing::BUILD_HISTOGRAM * bin.compiles as f32 / top.max(1) as f32;
let bar = egui::Rect::from_min_max( let bar = Rect::from_min_max(
egui::pos2(at(bin.from_ms), rect.bottom() - height), Pos2::new(at(bin.from_ms), rect.bottom() - height),
egui::pos2((at(bin.to_ms) - 1.0).max(at(bin.from_ms) + 1.0), rect.bottom()), Pos2::new((at(bin.to_ms) - 1.0).max(at(bin.from_ms) + 1.0), rect.bottom()),
); );
painter.rect_filled(bar, 1.0, style::BUILT.gamma_multiply(0.75)); painter.rect_filled(bar, 1.0, p.built);
} }
for (value, color) in [times.mean_ms, times.median_ms, times.p90_ms].into_iter().zip(colors) { 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); let x = at(value);
painter.rect_filled( painter.rect_filled(
egui::Rect::from_min_max(egui::pos2(x, rect.top()), egui::pos2(x + 2.0, rect.bottom())), Rect::from_min_max(Pos2::new(x, rect.top()), Pos2::new(x + 2.0, rect.bottom())),
0.0, 0.0,
color, color,
); );
@@ -186,22 +192,19 @@ fn histogram(ui: &mut Ui, times: &BuildTimes, low: f64, high: f64, colors: [Colo
/// The times along the bottom of a histogram: one mark every tenfold step. /// The times along the bottom of a histogram: one mark every tenfold step.
fn axis(ui: &mut Ui, low: f64, high: f64) { fn axis(ui: &mut Ui, low: f64, high: f64) {
let p = theme::ui(ui);
let width = ui.available_rect_before_wrap().width(); let width = ui.available_rect_before_wrap().width();
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, 14.0), Sense::hover()); let (rect, _) = ui.allocate_exact_size(egui::vec2(width, theme::drawing::BUILD_AXIS), Sense::hover());
let font = egui::TextStyle::Small.resolve(ui.style()); let font = egui::FontId::proportional(theme::px::SMALL);
let color = ui.visuals().weak_text_color();
for step in 0..=AXIS_TOP as i64 { for step in 0..=AXIS_TOP as i64 {
let value = step as f64; let value = step as f64;
if value < low || value > high { if value < low || value > high {
continue; continue;
} }
let x = rect.left() + rect.width() * ((value - low) / (high - low)) as f32; let x = rect.left() + rect.width() * ((value - low) / (high - low)) as f32;
ui.painter().text( let text = ms(10.0_f64.powf(value));
egui::pos2(x, rect.center().y), let galley = ui.painter().layout_no_wrap(text, font.clone(), p.muted);
egui::Align2::CENTER_CENTER, let x = x.clamp(rect.left(), rect.right() - galley.size().x);
ms(10.0_f64.powf(value)), ui.painter().galley(Pos2::new(x, rect.center().y - galley.size().y / 2.0), galley, p.muted);
font.clone(),
color,
);
} }
} }
+562 -178
View File
@@ -1,100 +1,540 @@
//! Colours and small drawings shared by the sections. //! Drawings shared by the panels: the grid, panels, cards, tables, bars and
//! chart keys. Every colour and size comes from [`crate::theme`].
use eframe::egui::{self, Align, Color32, Layout, Pos2, RichText, Sense, Shape, Stroke, Ui}; use std::sync::Arc;
/// Served from the cache. use eframe::egui::{self, Align, Align2, Color32, Galley, Layout, Pos2, Rect, RichText, Sense, Shape, Stroke, StrokeKind, Ui};
pub const CACHE: Color32 = Color32::from_rgb(0x4C, 0xAF, 0x50); use egui::TextWrapMode;
/// Compiled because the cache had nothing.
pub const BUILT: Color32 = Color32::from_rgb(0x42, 0xA5, 0xF5);
pub const NOT_CACHEABLE: Color32 = Color32::from_rgb(0xFF, 0xA7, 0x26);
pub const UNSUPPORTED: Color32 = Color32::from_rgb(0xAB, 0x47, 0xBC);
pub const NOT_COMPILE: Color32 = Color32::from_rgb(0x26, 0xA6, 0x9A);
/// Text colours that mean "good", "worth a look" and "bad", for the theme being drawn. use crate::theme::{self, px, space};
pub fn marks(dark: bool) -> [Color32; 3] {
if dark { /// The palette of the theme being drawn.
[ pub fn p(ui: &Ui) -> &'static theme::Palette {
Color32::from_rgb(0x3F, 0xB9, 0x50), theme::ui(ui)
Color32::from_rgb(0xD2, 0x99, 0x22), }
Color32::from_rgb(0xF8, 0x51, 0x49),
/// 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 { } else {
[ vec![
Color32::from_rgb(0x1A, 0x7F, 0x37), Pos2::new(at.x - 2.0, at.y - 4.0),
Color32::from_rgb(0x9A, 0x67, 0x00), at,
Color32::from_rgb(0xCF, 0x22, 0x2E), Pos2::new(at.x - 2.0, at.y + 4.0),
] ]
} };
painter.add(Shape::line(points, stroke));
*open
} }
/// The colour of a hit rate: green from 70%, yellow from 40%, red below. /// One cell of the counter strip: a small upper-case label, the number in mono, one line of
pub fn hit_rate_color(rate: Option<f64>, dark: bool) -> Color32 { /// small print and the change against the period before. Exactly `rect`; a hairline stands at
let [good, warn, bad] = marks(dark); /// its left unless it is the first of its row.
match rate { pub fn card(ui: &mut Ui, rect: Rect, first: bool, label: &str, number: &str, detail: &str, change: RichText, color: Color32) {
Some(rate) if rate >= 0.7 => good, let p = p(ui);
Some(rate) if rate >= 0.4 => warn, ui.allocate_rect(rect, Sense::hover());
Some(_) => bad, let inset = if first { 0.0 } else { 16.0 };
None => Color32::GRAY, 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());
} }
/// A titled section that starts open and can be folded away. // ---- Controls ----
pub fn section<R>(
ui: &mut Ui, /// One segmented control: `labels` side by side in one pill, the `chosen` one
id: &'static str, /// marked with the accent. Returns the segment that was clicked.
title: impl Into<egui::WidgetText>, pub fn segmented(ui: &mut Ui, id_salt: &'static str, labels: &[&str], chosen: usize) -> Option<usize> {
body: impl FnOnce(&mut Ui) -> R, let p = p(ui);
) -> Option<R> { let font = theme::medium(px::BODY);
ui.add_space(8.0); let widths: Vec<f32> = labels
// The body is indented, and then thinks it may run that much further right; .iter()
// hold it to the width that is left so nothing is pushed off the page. .map(|label| text_width(ui, label, font.clone()) + 2.0 * space::CONTROL_PAD)
let body_width = ui.available_rect_before_wrap().width() - ui.spacing().indent; .collect();
egui::CollapsingHeader::new(title.into().strong().size(17.0)) let total: f32 = widths.iter().sum();
.id_salt(id) let (rect, _) = ui.allocate_exact_size(egui::vec2(total, space::CONTROL_HEIGHT), Sense::hover());
.default_open(true) let painter = ui.painter();
.show(ui, |ui| { painter.rect(
ui.set_max_width(body_width); rect,
body(ui) 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
}) })
.body_returned .collect();
} natural.resize(columns, 0.0);
let mut galleys: Vec<Vec<(Option<Arc<Galley>>, String)>> = Vec::with_capacity(rows.len());
/// A message that must be noticed, in the colour of how bad it is. for row in rows {
pub fn banner(ui: &mut Ui, text: impl Into<RichText>, color: Color32) { let mut line = Vec::with_capacity(columns);
let mut text: RichText = text.into(); for (column, cell) in row.iter().enumerate() {
text = text.strong(); match cell {
// As wide as there is room, minus a little: text that wraps measures itself a few Cell::Marked(_, text) | Cell::Text(text) => {
// pixels wider, and a page that is told to fit exactly that wide grows each time. let galley = galley(ui, text.clone(), false, f32::INFINITY);
let width = ui.available_rect_before_wrap().width() - 2.0 * 8.0 - 6.0; let mark = if matches!(cell, Cell::Marked(..)) {
egui::Frame::NONE theme::drawing::LEGEND_SWATCH + 6.0
.fill(color.gamma_multiply(0.22)) } else {
.stroke(Stroke::new(1.0, color)) 0.0
.corner_radius(6.0) };
.inner_margin(8.0) natural[column] = natural[column].max(galley.size().x + 2.0 * pad + mark);
.show(ui, |ui| { line.push((Some(galley), text.text().to_owned()));
ui.set_min_width(width); }
ui.add(egui::Label::new(text).wrap()); 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(..)))
}); });
ui.add_space(6.0); 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 small coloured square in front of a legend entry.
pub fn swatch(ui: &mut Ui, color: Color32) { /// A bar filled from the left to `fraction` of its width (0 to 1), always `height` tall.
let (rect, _) = ui.allocate_exact_size(egui::vec2(10.0, 10.0), Sense::hover()); pub fn meter(ui: &mut Ui, height: f32, fraction: f64, fill: Color32) {
ui.painter().rect_filled(rect, 2.0, color); 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` /// 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 /// points break the line, so a gap never looks like a zero. `top` is the value
/// drawn at the top of the strip. /// drawn at the top of the strip.
pub fn sparkline(ui: &mut Ui, height: f32, values: &[Option<f64>], top: f64, color: Color32) { pub fn sparkline(ui: &mut Ui, height: f32, values: &[Option<f64>], top: f64, color: Color32) {
let (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_rect_before_wrap().width(), height), Sense::hover()); 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(); let painter = ui.painter();
painter.hline( painter.hline(rect.x_range(), rect.bottom() - 0.5, Stroke::new(1.0, p.grid));
rect.x_range(),
rect.bottom() - 0.5,
Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color),
);
if values.is_empty() || top <= 0.0 { if values.is_empty() || top <= 0.0 {
return; return;
} }
@@ -124,63 +564,6 @@ pub fn sparkline(ui: &mut Ui, height: f32, values: &[Option<f64>], top: f64, col
flush(&mut run, painter); flush(&mut run, painter);
} }
/// 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 (rect, _) = ui.allocate_exact_size(egui::vec2(ui.available_rect_before_wrap().width(), height), Sense::hover());
let painter = ui.painter();
painter.rect_filled(rect, height / 2.0, ui.visuals().extreme_bg_color);
let width = (rect.width() * fraction.clamp(0.0, 1.0) as f32).min(rect.width());
if width > 0.5 {
painter.rect_filled(
egui::Rect::from_min_max(rect.min, egui::pos2(rect.left() + width, rect.bottom())),
height / 2.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.
pub fn stacked_bar(ui: &mut Ui, height: f32, parts: &[(&'static str, u64, Color32)], total: u64) {
let (rect, response) = ui.allocate_exact_size(egui::vec2(ui.available_rect_before_wrap().width(), height), Sense::hover());
let painter = ui.painter();
painter.rect_filled(rect, 4.0, ui.visuals().extreme_bg_color);
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 = egui::Rect::from_min_max(egui::pos2(x, rect.top()), egui::pos2(x + width, rect.bottom()));
painter.rect_filled(part_rect, 4.0, *color);
x += width;
tip.push_str(&format!("{name}: {} ({})\n", crate::fmt::count(*part), crate::fmt::share(*part, total)));
}
}
if !tip.is_empty() {
response.clone().on_hover_text(tip.trim_end());
}
}
/// A short bar of fixed width showing hits against misses for one language.
pub fn hit_bar(ui: &mut Ui, width: f32, hits: u64, misses: u64) {
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, 12.0), Sense::hover());
let painter = ui.painter();
painter.rect_filled(rect, 3.0, ui.visuals().extreme_bg_color);
let total = hits + misses;
if total > 0 {
let hit_width = rect.width() * hits as f32 / total as f32;
painter.rect_filled(
egui::Rect::from_min_max(rect.min, egui::pos2(rect.left() + hit_width, rect.bottom())),
3.0,
CACHE,
);
}
}
/// Where a value between a tenth of a millisecond and 100 seconds sits on a /// 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. /// scale that lets 0.7 ms and 8 s both be seen.
pub fn log_fraction(ms: f64) -> f64 { pub fn log_fraction(ms: f64) -> f64 {
@@ -193,54 +576,55 @@ pub fn log_fraction(ms: f64) -> f64 {
position.clamp(0.02, 1.0) position.clamp(0.02, 1.0)
} }
/// A cell of [`table_row`]: how wide (`f32::INFINITY` for the width that is left), // ---- Chart keys ----
/// which side its content lines up with, and what draws it.
pub type Cell<'a> = (f32, egui::Align, Box<dyn FnOnce(&mut Ui) + 'a>);
/// Text in a cell, cut short if it is too long (or wrapped when `wrap` is set); /// What an entry of a chart's key stands for.
/// the whole text shows on hover. pub enum Mark {
pub fn text_cell(text: RichText, width: f32, right: bool, wrap: bool) -> Cell<'static> { /// A bar.
let hover = text.text().to_owned(); Fill(Color32),
let align = if right { egui::Align::Max } else { egui::Align::Min }; /// A line.
let draw = Box::new(move |ui: &mut Ui| { Line(Color32),
let label = egui::Label::new(text); /// A dashed line: a reset.
let label = if wrap { label.wrap() } else { label.truncate() }; Dashed(Color32),
ui.add(label).on_hover_text(hover); /// Time nothing was recorded in.
}); Band,
(width, align, draw)
} }
/// The width an `f32::INFINITY` cell gets in a row whose other cells are `fixed` wide. /// The swatch for one entry of a chart's key.
pub fn leftover(ui: &Ui, fixed: &[f32]) -> f32 { pub fn key(ui: &mut Ui, mark: Mark) {
let all = ui.available_rect_before_wrap().width(); let p = p(ui);
(all - fixed.iter().sum::<f32>() - ROW_SPACING * fixed.len() as f32).max(0.0) let (rect, _) = ui.allocate_exact_size(
} egui::vec2(theme::drawing::KEY_SWATCH, theme::drawing::KEY_SWATCH),
Sense::hover(),
pub const ROW_SPACING: f32 = 4.0;
/// One table row: cells of fixed widths from the left, one under another across rows.
pub fn table_row(ui: &mut Ui, cells: Vec<Cell<'_>>) {
let line = ui.text_style_height(&egui::TextStyle::Body) + 2.0;
let total = ui.available_rect_before_wrap().width();
let fixed: f32 = cells
.iter()
.filter(|(width, _, _)| width.is_finite())
.map(|(width, _, _)| *width)
.sum();
let rest = (total - fixed - ROW_SPACING * cells.len() as f32).max(0.0);
ui.allocate_ui_with_layout(
egui::vec2(total, line),
Layout::left_to_right(Align::Center),
|ui| {
ui.spacing_mut().item_spacing.x = ROW_SPACING;
for (width, align, draw) in cells {
let width = if width.is_finite() { width } else { rest };
let layout = match align {
Align::Max => Layout::right_to_left(Align::Center),
_ => Layout::left_to_right(Align::Center),
};
ui.allocate_ui_with_layout(egui::vec2(width, line), layout, |ui| draw(ui));
}
},
); );
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
}
}
+238 -112
View File
@@ -1,132 +1,258 @@
//! Where compiles went: one bar split by outcome, what happened inside the //! Where compiles went: one bar split by outcome, with a legend of counts and
//! built share, why some could not be cached, and how each language fared. //! shares; what happened inside the built share; and why some could not be
//! cached. How each language fared is its own panel ([`languages`]).
use eframe::egui::{self, RichText, Ui}; use std::sync::Arc;
use sccache_dash_api::View;
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::fmt;
use crate::style; use crate::style::{self, Cell};
use crate::theme;
pub fn section(ui: &mut Ui, view: &View, _dark: bool) { pub fn section(ui: &mut Ui, view: &View) {
let totals = &view.totals; let totals = &view.totals;
let p = theme::ui(ui);
// Five shares of every compiler call; timeouts, cache errors and forced // Five shares of every compiler call; timeouts, cache errors and forced
// recaches are inside the built share, as sccache counts them. // recaches are inside the built share, as sccache counts them.
let parts: [(&'static str, u64, egui::Color32); 5] = [ let parts: [(&'static str, u64, Color32); 5] = [
("From cache", totals.hits, style::CACHE), ("From cache", totals.hits, p.from_cache),
("Built", totals.misses, style::BUILT), ("Built", totals.misses, p.built),
("Not cacheable", totals.not_cacheable, style::NOT_CACHEABLE), ("Not cacheable", totals.not_cacheable, p.not_cacheable),
("Unsupported compiler", totals.unsupported_compiler, style::UNSUPPORTED), ("Unsupported compiler", totals.unsupported_compiler, p.unsupported),
("Not a compile", totals.not_compile, style::NOT_COMPILE), ("Not a compile", totals.not_compile, p.not_compile),
]; ];
let all: u64 = parts.iter().map(|(_, count, _)| count).sum(); let all: u64 = parts.iter().map(|(_, count, _)| count).sum();
let percents = fmt::shares(&parts.iter().map(|(_, count, _)| *count).collect::<Vec<_>>()); let percents = fmt::shares(&parts.iter().map(|(_, count, _)| *count).collect::<Vec<_>>());
style::section(ui, "where", "Where compiles went", |ui| { style::stacked_bar(ui, &parts, all);
style::stacked_bar(ui, 22.0, &parts, all); ui.add_space(6.0);
ui.add_space(4.0); let legend: Vec<Vec<Cell>> = parts
ui.horizontal_wrapped(|ui| { .iter()
for ((name, count, color), percent) in parts.iter().zip(&percents) { .zip(&percents)
style::swatch(ui, *color); .map(|((name, count, color), percent)| {
ui.label(*name); vec![
ui.label( Cell::Marked(*color, theme::body(*name)),
RichText::new(format!("{} · {percent}%", fmt::count(*count))).weak(), Cell::Text(theme::number(fmt::count(*count))),
); Cell::Text(theme::number(format!("{percent}%"))),
ui.add_space(8.0); ]
} })
}); .collect();
ui.add( style::table(ui, &[], &legend);
egui::Label::new(format!(
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", "Of the built: {} timeouts, {} cache errors, {} forced recaches, {} failed to compile",
fmt::count(totals.timeouts), fmt::count(totals.timeouts),
fmt::count(totals.errors()), fmt::count(totals.errors()),
fmt::count(totals.forced_recaches), fmt::count(totals.forced_recaches),
fmt::count(totals.compile_fails) fmt::count(totals.compile_fails)
)) ),
.wrap(), ),
); ));
if !view.not_cached.is_empty() {
ui.add_space(6.0);
ui.label(RichText::new("Why compiles could not be cached").strong());
for (reason, count) in &view.not_cached {
style::table_row(
ui,
vec![
style::text_cell(RichText::new(reason.as_str()), f32::INFINITY, false, false),
style::text_cell(RichText::new(fmt::count(*count)), 72.0, true, false),
style::text_cell(
RichText::new(fmt::share(*count, totals.not_cacheable)),
56.0,
true,
false,
),
],
);
}
}
if !view.languages.is_empty() {
ui.add_space(6.0);
ui.label(RichText::new("By language").strong());
languages(ui, view);
}
});
} }
/// One row per language: hits, misses, errors, hit rate and a small bar. /// One reason laid out for a width: its line, and the two small paragraphs when it is open.
fn languages(ui: &mut Ui, view: &View) { struct Block {
let dark = ui.visuals().dark_mode; name: Arc<Galley>,
let text_color = ui.visuals().text_color(); count: Arc<Galley>,
let [_, _, bad] = style::marks(dark); share: Arc<Galley>,
// Narrower cells on a phone, so the whole row fits. /// `None` while the reason is closed.
let (name, hits, misses, errors, rate) = if ui.available_rect_before_wrap().width() < 480.0 { meaning: Option<Arc<Galley>>,
(68.0, 56.0, 64.0, 52.0, 48.0) /// `None` when closed, or when sccache gives nothing to do.
} else { action: Option<Arc<Galley>>,
(130.0, 80.0, 80.0, 72.0, 76.0) /// The line: at least a control tall, taller when the name wraps.
}; row: f32,
let widths = [name, hits, misses, errors, rate]; open: bool,
let bar = (style::leftover(ui, &widths) - style::ROW_SPACING).max(0.0); }
let weak = |text: &'static str, width| style::text_cell(RichText::new(text).small().weak(), width, true, false);
style::table_row( impl Block {
ui, fn entry(&self) -> disclosure::Entry {
vec![ disclosure::Entry {
style::text_cell(RichText::new("").small(), name, false, false), row: self.row,
weak("Hits", hits), open: self.open,
weak("Misses", misses), meaning: self.meaning.as_ref().map_or(0.0, |g| g.size().y),
weak("Errors", errors), action: self.action.as_ref().map(|g| g.size().y),
weak("Hit rate", rate), }
(f32::INFINITY, egui::Align::Min, Box::new(|_ui| {})),
],
);
for language in &view.languages {
let language_rate = crate::overtime::hit_rate(language.hits, language.misses);
let (language_hits, language_misses) = (language.hits, language.misses);
style::table_row(
ui,
vec![
style::text_cell(RichText::new(&language.name).strong(), name, false, false),
style::text_cell(RichText::new(fmt::count(language.hits)), hits, true, false),
style::text_cell(RichText::new(fmt::count(language.misses)), misses, true, false),
style::text_cell(
RichText::new(fmt::count(language.errors))
.color(if language.errors > 0 { bad } else { text_color }),
errors,
true,
false,
),
style::text_cell(
RichText::new(fmt::percent(language_rate))
.color(style::hit_rate_color(language_rate, dark)),
rate,
true,
false,
),
(
f32::INFINITY,
egui::Align::Min,
Box::new(move |ui| style::hit_bar(ui, bar, language_hits, language_misses)),
),
],
);
} }
} }
/// 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}}
+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); });