#![deny(missing_docs)]
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
pub struct ReadmeDoctests;
use std::path::Path;
use frus_core::{Color, Scene, Size};
use frus_widgets::{build_deferred, build_ui, Runtime, ScrollPhysics, Theme, Ui, Widget};
pub struct Snapshot {
pub width: u32,
pub height: u32,
pub rgba: Vec<u8>,
}
pub fn render_scene(scene: &Scene, width: u32, height: u32, clear: Color) -> Option<Snapshot> {
let frame = frus_gpu::render_offscreen(scene, width, height, clear)?;
Some(Snapshot {
width: frame.width,
height: frame.height,
rgba: frame.rgba,
})
}
pub fn render_widget<Msg: Clone + 'static>(
root: &dyn Widget<Msg>,
width: u32,
height: u32,
theme: &Theme,
) -> Option<Snapshot> {
let mut stage = Stage::new(width, height).theme(theme.clone());
stage.settle(root);
stage.render(root)
}
pub struct Stage {
pub runtime: Runtime,
pub theme: Theme,
width: u32,
height: u32,
}
impl Stage {
pub fn new(width: u32, height: u32) -> Self {
Self {
runtime: Runtime::default(),
theme: Theme::dark(),
width,
height,
}
}
pub fn theme(mut self, theme: Theme) -> Self {
self.theme = theme;
self
}
pub fn size(&self) -> Size {
Size::new(self.width as f32, self.height as f32)
}
pub fn build<'a, Msg: Clone + 'static>(&'a self, root: &'a dyn Widget<Msg>) -> Ui<Msg> {
self.runtime.states.begin_build();
build_deferred(root, &self.theme, &self.runtime);
let ui = build_ui(root, self.size(), &self.runtime, &self.theme);
self.runtime.states.end_frame();
ui
}
pub fn advance<Msg: Clone + 'static>(&mut self, root: &dyn Widget<Msg>, dt: f32) -> bool {
let (regions, refresh_areas, dismissables, interactive, sheets) = {
let ui = self.build(root);
(
ui.scroll_regions().to_vec(),
ui.refresh_areas().to_vec(),
ui.dismissables().to_vec(),
ui.interactive_bounds(),
ui.sheets().to_vec(),
)
};
self.runtime.time += dt;
self.runtime.sync_pages(®ions);
let (dismiss_moving, _dismissed) = self.runtime.advance_dismiss(&dismissables, dt);
let (sheets_moving, _closed) = self.runtime.advance_sheets(&sheets, dt);
let mut handed = false;
for (list, velocity) in self.runtime.take_sheet_handovers() {
if let Some(area) = regions.iter().find(|area| area.id == list) {
let physics = area.physics_or(ScrollPhysics::default());
handed |= self.runtime.fling_scroll(*area, physics, (0.0, velocity));
}
}
self.runtime.advance(dt)
| self.runtime.advance_leaving(dt)
| self.runtime.advance_switchers(root, dt)
| self.runtime.advance_values(root, dt)
| self.runtime.advance_colors(root, dt)
| self.runtime.advance_sizes(root, dt)
| self.runtime.advance_radii(root, dt)
| self.runtime.advance_paddings(root, dt)
| self.runtime.advance_offsets(root, dt)
| self.runtime.advance_pins(root, dt)
| self.runtime.advance_fractions(root, dt)
| self.runtime.advance_text_styles(root, dt)
| self.runtime.advance_transforms(root, dt)
| self
.runtime
.advance_scroll(®ions, ScrollPhysics::default(), dt)
| self.runtime.advance_glow(dt)
| self.runtime.advance_refresh(&refresh_areas, dt)
| self.runtime.advance_interactive(&interactive, dt)
| dismiss_moving
| sheets_moving
| handed
}
pub fn settle<Msg: Clone + 'static>(&mut self, root: &dyn Widget<Msg>) {
self.advance(root, 0.0);
}
pub fn advance_by<Msg: Clone + 'static>(
&mut self,
root: &dyn Widget<Msg>,
dt: f32,
steps: usize,
) {
for _ in 0..steps {
self.advance(root, dt);
}
}
pub fn render<Msg: Clone + 'static>(&self, root: &dyn Widget<Msg>) -> Option<Snapshot> {
let ui = self.build(root);
render_scene(ui.scene(), self.width, self.height, self.theme.background)
}
}
impl Snapshot {
pub fn pixel(&self, x: u32, y: u32) -> [u8; 4] {
assert!(x < self.width && y < self.height, "pixel out of frame");
let i = ((y * self.width + x) * 4) as usize;
[
self.rgba[i],
self.rgba[i + 1],
self.rgba[i + 2],
self.rgba[i + 3],
]
}
pub fn lit_pixels(&self, threshold: u8) -> usize {
self.rgba
.as_chunks::<4>()
.0
.iter()
.filter(|px| px[0] > threshold || px[1] > threshold || px[2] > threshold)
.count()
}
pub fn diff_count(&self, other: &Snapshot, channel_tolerance: u8) -> usize {
assert_eq!(
(self.width, self.height),
(other.width, other.height),
"the snapshots have different sizes"
);
self.rgba
.as_chunks::<4>()
.0
.iter()
.zip(other.rgba.as_chunks::<4>().0.iter())
.filter(|(a, b)| {
a.iter()
.zip(b.iter())
.any(|(ca, cb)| ca.abs_diff(*cb) > channel_tolerance)
})
.count()
}
pub fn write_png(&self, path: impl AsRef<Path>) {
write_png(path.as_ref(), self);
}
pub fn assert_golden(&self, path: impl AsRef<Path>) {
self.assert_golden_with(path, 2, 0);
}
pub fn assert_golden_with(
&self,
path: impl AsRef<Path>,
channel_tolerance: u8,
max_diff_pixels: usize,
) {
let path = path.as_ref();
let update = std::env::var_os("FRUS_UPDATE_GOLDENS").is_some_and(|v| v == "1");
if update || !path.exists() {
write_png(path, self);
if !update {
eprintln!(
"golden created: {} — read it over, then commit it",
path.display()
);
}
return;
}
let golden = read_png(path);
if (golden.width, golden.height) != (self.width, self.height) {
let actual = actual_path(path);
write_png(&actual, self);
panic!(
"golden {}: size {}×{} ≠ rendered {}×{} (the rendering was written to {})",
path.display(),
golden.width,
golden.height,
self.width,
self.height,
actual.display()
);
}
let diff = self.diff_count(&golden, channel_tolerance);
if diff > max_diff_pixels {
let actual = actual_path(path);
write_png(&actual, self);
panic!(
"golden {}: {diff} pixel(s) differ (tolerance {max_diff_pixels}) — the \
rendering was written to {}; rerun with FRUS_UPDATE_GOLDENS=1 to accept it",
path.display(),
actual.display()
);
}
}
}
fn actual_path(golden: &Path) -> std::path::PathBuf {
golden.with_extension("actual.png")
}
fn write_png(path: &Path, snapshot: &Snapshot) {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).expect("creating the goldens folder");
}
let file =
std::fs::File::create(path).unwrap_or_else(|e| panic!("creating {}: {e}", path.display()));
let mut encoder = png::Encoder::new(
std::io::BufWriter::new(file),
snapshot.width,
snapshot.height,
);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder.write_header().expect("PNG header");
writer
.write_image_data(&snapshot.rgba)
.expect("writing the PNG");
}
fn read_png(path: &Path) -> Snapshot {
let file =
std::fs::File::open(path).unwrap_or_else(|e| panic!("reading {}: {e}", path.display()));
let decoder = png::Decoder::new(std::io::BufReader::new(file));
let mut reader = decoder.read_info().expect("PNG info");
let mut buf = vec![0; reader.output_buffer_size()];
let info = reader.next_frame(&mut buf).expect("PNG frame");
assert_eq!(
info.color_type,
png::ColorType::Rgba,
"the golden is not RGBA"
);
buf.truncate(info.buffer_size());
Snapshot {
width: info.width,
height: info.height,
rgba: buf,
}
}
#[cfg(test)]
mod tests {
use frus_core::Size;
use frus_widgets::{
build_ui, button, row, text, Align, Card, Checkbox, Container, Flex, Icon, Icons, Runtime,
Theme, Widget,
};
#[test]
fn a_real_screen_still_batches() {
let mut rows: Vec<Box<dyn Widget<()>>> = Vec::new();
for i in 0..12 {
rows.push(Box::new(
row![
Checkbox::new(i % 2 == 0),
text(format!("Task number {i}")).size(15.0),
Container::new().flex(1.0),
Icon::new(Icons::CLOSE).size(16.0),
button("Open", ()),
]
.gap(12.0)
.align(Align::Center)
.height(48.0),
));
}
let mut list = Flex::column().gap(8.0);
for r in rows {
list = list.child_boxed(r);
}
let screen = Container::new()
.width(400.0)
.height(800.0)
.padding(16.0)
.child(Card::new().padding(12.0).child(list));
let ui = build_ui(
&screen,
Size::new(400.0, 800.0),
&Runtime::default(),
&Theme::default(),
);
let calls = frus_gpu::draw_calls(ui.scene());
let primitives = ui.scene().primitives().len();
assert!(
calls <= 4,
"{calls} draw calls for {primitives} primitives: batching broke down"
);
}
}