use std::{fmt, path::Path};
use meo_canvas_core::{
EncodeOptions, Error, ImageFormat, ImageWarning, PreparedEncode,
RenderedCanvas, Renderer, diagnostic::Diagnostic,
};
use meo_canvas_scene::{
OnImageError, Scene, SceneError, Size, node::HttpOptions,
};
use crate::{
ColorSpace, ColorType, Element, IntoElements, Style, Styled,
element::write_page,
};
fn collect(children: impl IntoElements) -> Vec<Element> {
let mut out = Vec::new();
children.write_elements(&mut out);
out
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PageInfo {
pub index: u32,
pub count: u32,
pub progress: f32,
pub cycle: f32,
pub time: f32,
}
impl PageInfo {
fn new(index: u32, count: u32, fps: f32) -> Self {
let spread = if count > 1 {
#[expect(
clippy::cast_precision_loss,
reason = "a page count large enough to lose precision in an f32 is one no renderer would finish"
)]
{
(index as f32, (count - 1) as f32, count as f32)
}
} else {
(0.0, 1.0, 1.0)
};
Self {
index,
count,
progress: spread.0 / spread.1,
cycle: spread.0 / spread.2,
time: spread.0 / fps,
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum BuildError {
Sequence(SequenceError),
Scene(SceneError),
Render(Error),
Write(std::io::Error),
Format(String),
}
impl fmt::Display for BuildError {
fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Sequence(error) => error.fmt(out),
Self::Scene(error) => error.fmt(out),
Self::Render(error) => error.fmt(out),
Self::Write(error) => error.fmt(out),
Self::Format(path) => write!(
out,
"cannot tell the format from {path:?}; name the file with an extension such as .png, or use `to_file_as`"
),
}
}
}
impl std::error::Error for BuildError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Sequence(error) => Some(error),
Self::Scene(error) => Some(error),
Self::Render(error) => Some(error),
Self::Write(error) => Some(error),
Self::Format(_) => None,
}
}
}
impl From<Error> for BuildError {
fn from(error: Error) -> Self {
Self::Render(error)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SequenceError {
CountAndDuration,
BuilderWithoutLength,
LengthWithoutBuilder,
NoPages,
}
impl fmt::Display for SequenceError {
fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
let said = match self {
Self::CountAndDuration => {
"name a page count or a duration, not both; they are two spellings of one number"
}
Self::BuilderWithoutLength => {
"a page builder needs `pages` or `duration`; without one there is no sequence to build"
}
Self::LengthWithoutBuilder => {
"`pages` and `duration` describe a sequence, so there has to be a page builder to vary"
}
Self::NoPages => "a render has at least one page",
};
out.write_str(said)
}
}
impl std::error::Error for SequenceError {}
enum Content {
Fixed(Vec<Element>),
Built(Box<dyn Fn(PageInfo) -> Vec<Element>>),
}
impl fmt::Debug for Content {
fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Fixed(children) => {
out.debug_tuple("Fixed").field(children).finish()
}
Self::Built(_) => out.write_str("Built(<closure>)"),
}
}
}
#[derive(Debug)]
pub struct Root {
width: f32,
height: f32,
on_image_error: OnImageError,
http: HttpOptions,
content_height: bool,
scale: f32,
style: Style,
name: Option<String>,
gpu: Option<bool>,
color_type: Option<ColorType>,
color_space: Option<ColorSpace>,
content: Content,
pages: Option<u32>,
duration: Option<f32>,
fps: f32,
}
impl Root {
pub const DEFAULT_FPS: f32 = 30.0;
pub const DEFAULT_SCALE: f32 = 1.0;
#[must_use]
pub const fn new(width: f32) -> Self {
Self {
width,
height: 0.0,
content_height: true,
scale: Self::DEFAULT_SCALE,
on_image_error: OnImageError::Placeholder,
http: HttpOptions::new(),
style: Style::new()
.display(meo_canvas_scene::style::layout::Display::Flex),
name: None,
gpu: None,
color_type: None,
color_space: None,
content: Content::Fixed(Vec::new()),
pages: None,
duration: None,
fps: Self::DEFAULT_FPS,
}
}
#[must_use]
pub const fn height(mut self, height: f32) -> Self {
self.height = height;
self.content_height = false;
self
}
#[must_use]
pub const fn min_height(mut self, floor: f32) -> Self {
if self.content_height {
self.height = floor;
}
self
}
#[must_use]
pub const fn scale(mut self, scale: f32) -> Self {
self.scale = scale;
self
}
#[must_use]
pub fn name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
#[must_use]
pub const fn gpu(mut self, gpu: bool) -> Self {
self.gpu = Some(gpu);
self
}
#[must_use]
pub const fn on_image_error(mut self, policy: OnImageError) -> Self {
self.on_image_error = policy;
self
}
#[must_use]
pub fn http_options(mut self, http: HttpOptions) -> Self {
self.http = http;
self
}
#[must_use]
pub const fn color_type(mut self, color_type: ColorType) -> Self {
self.color_type = Some(color_type);
self
}
#[must_use]
pub const fn color_space(mut self, color_space: ColorSpace) -> Self {
self.color_space = Some(color_space);
self
}
#[must_use]
pub fn children(mut self, children: impl IntoElements) -> Self {
self.content = Content::Fixed(collect(children));
self
}
#[must_use]
pub fn page_builder<C: IntoElements>(
mut self,
builder: impl Fn(PageInfo) -> C + 'static,
) -> Self {
self.content =
Content::Built(Box::new(move |page| collect(builder(page))));
self
}
#[must_use]
pub const fn pages(mut self, pages: u32) -> Self {
self.pages = Some(pages);
self
}
#[must_use]
pub const fn duration(mut self, seconds: f32) -> Self {
self.duration = Some(seconds);
self
}
#[must_use]
pub const fn fps(mut self, fps: f32) -> Self {
self.fps = fps;
self
}
fn sequence(&self) -> Result<(u32, f32), SequenceError> {
let built = matches!(self.content, Content::Built(_));
if self.pages.is_some() && self.duration.is_some() {
return Err(SequenceError::CountAndDuration);
}
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "a duration long enough to overflow a u32 of pages is one no renderer would finish, and a negative one is refused as a count below one"
)]
let asked = self
.pages
.or_else(|| self.duration.map(|s| (s * self.fps).ceil() as u32));
let Some(count) = asked else {
if built {
return Err(SequenceError::BuilderWithoutLength);
}
return Ok((1, self.fps));
};
if !built {
return Err(SequenceError::LengthWithoutBuilder);
}
if count == 0 {
return Err(SequenceError::NoPages);
}
Ok((count, self.fps))
}
pub fn into_scene(self) -> Result<(Scene, Vec<Diagnostic>), BuildError> {
let (count, fps) = self.sequence().map_err(BuildError::Sequence)?;
let size = Size::new(self.width, self.height);
if !meo_canvas_scene::size_is_pixels(size) {
return Err(BuildError::Scene(SceneError::canvas_size(
self.width,
self.height,
)));
}
let mut scene = Scene::new(size);
scene.content_height = self.content_height;
scene.scale = self.scale;
scene.gpu = self.gpu;
scene.on_image_error = self.on_image_error;
scene.http = self.http;
scene.color_type = self.color_type;
scene.color_space = self.color_space;
let page_root = |children: Vec<Element>| {
let root = Element::new(meo_canvas_scene::node::NodeKind::Box)
.with_style(self.style.clone())
.children(children);
match &self.name {
Some(name) => root.name(name.clone()),
None => root,
}
};
let mut found: Vec<Diagnostic> = Vec::new();
let write = |scene: &mut Scene,
first: bool,
children: Vec<Element>,
found: &mut Vec<Diagnostic>|
-> Result<(), BuildError> {
let root = if first {
scene
.root()
.ok_or(BuildError::Sequence(SequenceError::NoPages))?
} else {
scene.push_page().map_err(BuildError::Scene)?
};
write_page(scene, root, page_root(children), found)
.map_err(BuildError::Scene)
};
match &self.content {
Content::Fixed(children) => {
write(&mut scene, true, children.clone(), &mut found)?;
}
Content::Built(builder) => {
for index in 0..count {
let children = builder(PageInfo::new(index, count, fps));
write(&mut scene, index == 0, children, &mut found)?;
}
}
}
Ok((scene, found))
}
pub fn render(self, renderer: &Renderer) -> Result<Canvas, BuildError> {
let (scene, mut diagnostics) = self.into_scene()?;
let painted = renderer.render(&scene)?;
diagnostics.extend_from_slice(painted.diagnostics());
Ok(Canvas {
painted,
diagnostics,
})
}
}
impl Styled for Root {
fn style_mut(&mut self) -> &mut Style {
&mut self.style
}
}
#[derive(Debug)]
pub struct Canvas {
painted: RenderedCanvas,
diagnostics: Vec<Diagnostic>,
}
impl Canvas {
#[must_use]
pub fn diagnostics(&self) -> &[Diagnostic] {
&self.diagnostics
}
pub fn to_buffer(
&mut self,
format: ImageFormat,
) -> Result<Vec<u8>, BuildError> {
self.to_buffer_with(format, &EncodeOptions::default())
}
pub fn to_buffer_with(
&mut self,
format: ImageFormat,
options: &EncodeOptions,
) -> Result<Vec<u8>, BuildError> {
Ok(self.painted.to_buffer(format, options)?)
}
pub fn prepare_encode(
&mut self,
format: ImageFormat,
options: &EncodeOptions,
) -> Result<PreparedEncode, BuildError> {
Ok(self.painted.prepare_encode(format, options)?)
}
pub fn to_file(
&mut self,
path: impl AsRef<Path>,
) -> Result<(), BuildError> {
let path = path.as_ref();
let format = path
.extension()
.and_then(|extension| extension.to_str())
.and_then(ImageFormat::from_named)
.ok_or_else(|| BuildError::Format(path.display().to_string()))?;
self.to_file_with(path, format, &EncodeOptions::default())
}
pub fn to_file_as(
&mut self,
path: impl AsRef<Path>,
format: ImageFormat,
) -> Result<(), BuildError> {
self.to_file_with(path, format, &EncodeOptions::default())
}
pub fn to_file_with(
&mut self,
path: impl AsRef<Path>,
format: ImageFormat,
options: &EncodeOptions,
) -> Result<(), BuildError> {
let path = path.as_ref();
match std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
{
Ok(file) => {
drop(file);
drop(std::fs::remove_file(path));
}
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
drop(
std::fs::OpenOptions::new()
.write(true)
.open(path)
.map_err(BuildError::Write)?,
);
}
Err(error) => return Err(BuildError::Write(error)),
}
Ok(self.painted.prepare_encode(format, options)?.write(path)?)
}
pub fn to_url(
&mut self,
format: ImageFormat,
) -> Result<String, BuildError> {
let bytes = self.to_buffer(format)?;
Ok(format!(
"data:{};base64,{}",
format.media_type(),
base64(&bytes)
))
}
pub fn to_data_url(
&mut self,
format: ImageFormat,
quality: Option<f32>,
) -> Result<String, BuildError> {
let options = EncodeOptions {
quality,
..EncodeOptions::default()
};
let bytes = self.to_buffer_with(format, &options)?;
Ok(format!(
"data:{};base64,{}",
format.media_type(),
base64(&bytes)
))
}
#[must_use]
pub fn page_count(&self) -> usize {
self.painted.page_count()
}
#[must_use]
pub const fn scale(&self) -> f32 {
self.painted.scale()
}
#[must_use]
pub fn warnings(&self) -> &[ImageWarning] {
self.painted.warnings()
}
#[must_use]
pub const fn gpu(&self) -> bool {
self.painted.gpu()
}
#[must_use]
pub fn engine(&self) -> &'static str {
self.painted.engine()
}
}
fn base64(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let (a, b, c) = (
u32::from(chunk[0]),
chunk.get(1).map_or(0, |byte| u32::from(*byte)),
chunk.get(2).map_or(0, |byte| u32::from(*byte)),
);
let triple = (a << 16) | (b << 8) | c;
out.push(ALPHABET[((triple >> 18) & 63) as usize] as char);
out.push(ALPHABET[((triple >> 12) & 63) as usize] as char);
out.push(if chunk.len() > 1 {
ALPHABET[((triple >> 6) & 63) as usize] as char
} else {
'='
});
out.push(if chunk.len() > 2 {
ALPHABET[(triple & 63) as usize] as char
} else {
'='
});
}
out
}
#[cfg(test)]
mod tests {
use meo_canvas_scene::node::NodeKind;
use super::{BuildError, PageInfo, Root, SequenceError};
use crate::{
Box, ColorSpace, ColorType, Column, EncodeOptions, Format, Renderer,
Row, Styled, Text, hex_rgb, px,
};
#[test]
fn a_build_error_hands_back_what_went_wrong_underneath_it() {
use std::error::Error as _;
let refused = Root::new(f32::NAN)
.children([Box::new()])
.into_scene()
.err()
.unwrap_or_else(|| unreachable!("a NaN width is refused"));
let source = refused
.source()
.unwrap_or_else(|| unreachable!("the scene error is underneath"));
assert!(
source
.downcast_ref::<meo_canvas_scene::SceneError>()
.is_some(),
"the cause came back as something other than the scene error"
);
let io = BuildError::Write(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"no",
));
let kind = io
.source()
.and_then(|error| error.downcast_ref::<std::io::Error>())
.map(std::io::Error::kind);
assert_eq!(kind, Some(std::io::ErrorKind::PermissionDenied));
}
#[test]
fn a_written_file_is_the_buffer_and_a_bad_path_keeps_its_error_kind() {
use std::error::Error as _;
let renderer = Renderer::new();
let mut canvas = Root::new(16.0)
.height(8.0)
.render(&renderer)
.unwrap_or_else(|error| unreachable!("{error}"));
let expected = canvas
.to_buffer(Format::Png)
.unwrap_or_else(|error| unreachable!("{error}"));
let path = std::env::temp_dir().join("meo-canvas-root-to-file.png");
canvas
.to_file(&path)
.unwrap_or_else(|error| unreachable!("{error}"));
let written = std::fs::read(&path)
.unwrap_or_else(|error| unreachable!("{error}"));
assert_eq!(written, expected, "the file and the buffer differ");
std::fs::remove_file(&path)
.unwrap_or_else(|error| unreachable!("{error}"));
let missing = std::env::temp_dir()
.join("meo-canvas-no-such-directory")
.join("out.png");
let refused = canvas.to_file(&missing);
let Err(error) = refused else {
unreachable!("writing into a missing directory succeeded");
};
assert!(
matches!(error, BuildError::Write(_)),
"a missing directory reported {error:?} rather than a write error"
);
let kind = error
.source()
.and_then(|cause| cause.downcast_ref::<std::io::Error>())
.map(std::io::Error::kind);
assert_eq!(kind, Some(std::io::ErrorKind::NotFound));
}
#[test]
fn a_refused_encode_leaves_the_previous_file_alone() {
let renderer = Renderer::new();
let mut canvas = Root::new(16.0)
.height(8.0)
.render(&renderer)
.unwrap_or_else(|error| unreachable!("{error}"));
let path = std::env::temp_dir().join("meo-canvas-not-clobbered.png");
canvas
.to_file(&path)
.unwrap_or_else(|error| unreachable!("{error}"));
let before = std::fs::read(&path)
.unwrap_or_else(|error| unreachable!("{error}"));
assert!(!before.is_empty(), "the first write produced nothing");
let refused = canvas.to_file_with(
&path,
Format::Png,
&EncodeOptions {
fps: Some(30.0),
..EncodeOptions::default()
},
);
assert!(refused.is_err(), "a frame rate on a PNG was accepted");
let after = std::fs::read(&path)
.unwrap_or_else(|error| unreachable!("{error}"));
assert_eq!(
after, before,
"a refused encode changed the file that was already there"
);
std::fs::remove_file(&path)
.unwrap_or_else(|error| unreachable!("{error}"));
}
#[test]
fn a_refused_encode_leaves_no_file_where_there_was_none() {
let renderer = Renderer::new();
let mut canvas = Root::new(16.0)
.height(8.0)
.render(&renderer)
.unwrap_or_else(|error| unreachable!("{error}"));
let path = std::env::temp_dir().join("meo-canvas-no-residue.png");
drop(std::fs::remove_file(&path));
let refused = canvas.to_file_with(
&path,
Format::Png,
&EncodeOptions {
fps: Some(30.0),
..EncodeOptions::default()
},
);
assert!(refused.is_err(), "a frame rate on a PNG was accepted");
assert!(
!path.exists(),
"a refused encode left a file at a path that had none"
);
}
#[test]
fn a_root_whose_width_is_not_a_length_is_refused() {
for width in [f32::NAN, -100.0, f32::INFINITY] {
let refused = Root::new(width).children([Box::new()]).into_scene();
assert!(
matches!(
refused,
Err(BuildError::Scene(
meo_canvas_scene::SceneError::CanvasSize { .. }
))
),
"a width of {width} was accepted"
);
}
let refused = Root::new(10.0)
.height(-1.0)
.children([Box::new()])
.into_scene();
assert!(matches!(
refused,
Err(BuildError::Scene(
meo_canvas_scene::SceneError::CanvasSize { .. }
))
));
assert!(Root::new(0.0).children([Box::new()]).into_scene().is_ok());
}
#[test]
fn to_file_accepts_the_extensions_the_javascript_surface_does() {
let dir = std::env::temp_dir()
.join(format!("meo-to-file-{}", std::process::id()));
std::fs::create_dir_all(&dir)
.unwrap_or_else(|error| unreachable!("{error}"));
let mut canvas = Root::new(8.0)
.height(4.0)
.children(Box::new())
.render(&Renderer::new())
.unwrap_or_else(|error| unreachable!("{error}"));
for extension in ["png", "raw", "RAW"] {
let path = dir.join(format!("out.{extension}"));
assert!(
canvas.to_file(&path).is_ok(),
".{extension} should name a format"
);
}
assert_eq!(
std::fs::metadata(dir.join("out.raw"))
.unwrap_or_else(|error| unreachable!("{error}"))
.len(),
8 * 4 * 4
);
for extension in ["bin", "nonsense"] {
let path = dir.join(format!("out.{extension}"));
assert!(
matches!(canvas.to_file(&path), Err(BuildError::Format(_))),
".{extension} names no format"
);
}
std::fs::remove_dir_all(&dir).ok();
}
fn scene_of(root: Root) -> meo_canvas_scene::Scene {
root.into_scene()
.map_or_else(|error| unreachable!("{error}"), |(scene, _)| scene)
}
#[test]
fn a_root_takes_its_size_and_defaults_the_scale() {
let scene = scene_of(Root::new(120.0).height(60.0));
assert_eq!(scene.size.width.to_bits(), 120.0_f32.to_bits());
assert_eq!(scene.size.height.to_bits(), 60.0_f32.to_bits());
assert_eq!(scene.scale.to_bits(), Root::DEFAULT_SCALE.to_bits());
}
#[test]
fn the_scale_reaches_the_scene_without_moving_the_layout() {
let scene = scene_of(Root::new(10.0).height(10.0).scale(3.0));
assert_eq!(scene.scale.to_bits(), 3.0_f32.to_bits());
}
#[test]
fn the_root_is_the_page_rather_than_a_box_inside_it() {
let scene = scene_of(
Root::new(10.0)
.height(10.0)
.background_color(hex_rgb(0x10_10_14))
.children(Row::new()),
);
let root = scene
.get(scene.pages[0])
.unwrap_or_else(|| unreachable!("the scene has no root"));
assert_eq!(root.paint.background_color, hex_rgb(0x10_10_14).into());
assert_eq!(root.children.len(), 1);
}
#[test]
fn children_take_one_or_many_and_skip_what_did_not_render() {
let one = scene_of(Root::new(10.0).height(10.0).children(Row::new()));
let many = scene_of(
Root::new(10.0)
.height(10.0)
.children([Row::new(), Column::new()]),
);
let conditional = scene_of(Root::new(10.0).height(10.0).children([
Some(Row::new()),
None,
Some(Column::new()),
]));
let count = |scene: &meo_canvas_scene::Scene| {
scene
.get(scene.pages[0])
.map_or(0, |root| root.children.len())
};
assert_eq!(count(&one), 1);
assert_eq!(count(&many), 2);
assert_eq!(count(&conditional), 2);
}
#[test]
fn a_flat_setter_writes_the_same_field_the_style_does() {
let scene =
scene_of(Root::new(10.0).height(10.0).children(
Row::new().gap(px(4.0)).padding(crate::all(px(8.0))),
));
let root = scene
.get(scene.pages[0])
.unwrap_or_else(|| unreachable!("the scene has no root"));
let child = scene
.get(root.children[0])
.unwrap_or_else(|| unreachable!("the root has no child"));
assert_eq!(child.layout.gap.0, meo_canvas_scene::Length::Points(4.0));
assert_eq!(
child.layout.padding.top,
meo_canvas_scene::Length::Points(8.0)
);
}
#[test]
fn a_name_reaches_the_node_it_was_written_on() {
let scene = scene_of(
Root::new(10.0)
.height(10.0)
.name("page")
.children(Row::new().name("card")),
);
let root = scene
.get(scene.pages[0])
.unwrap_or_else(|| unreachable!("the scene has no root"));
let child = scene
.get(root.children[0])
.unwrap_or_else(|| unreachable!("the root has no child"));
assert_eq!(root.name.as_deref(), Some("page"));
assert_eq!(child.name.as_deref(), Some("card"));
}
#[test]
fn a_name_is_absent_when_none_was_given() {
let scene = scene_of(Root::new(10.0).height(10.0).children(Row::new()));
let root = scene
.get(scene.pages[0])
.unwrap_or_else(|| unreachable!("the scene has no root"));
assert_eq!(root.name, None);
}
#[test]
fn the_surface_options_reach_the_scene_and_stay_absent_otherwise() {
let silent = scene_of(Root::new(10.0).height(10.0));
let stated = scene_of(
Root::new(10.0)
.height(10.0)
.gpu(false)
.color_type(ColorType::F32)
.color_space(ColorSpace::DisplayP3),
);
assert_eq!(silent.gpu, None);
assert_eq!(silent.color_type, None);
assert_eq!(silent.color_space, None);
assert_eq!(stated.gpu, Some(false));
assert_eq!(stated.color_type, Some(ColorType::F32));
assert_eq!(stated.color_space, Some(ColorSpace::DisplayP3));
}
#[test]
fn the_two_rasterisers_do_not_draw_the_same_pixels() {
let renderer = Renderer::new();
let rounded = || {
Box::new()
.size(px(120.0), px(60.0))
.border_radius(24.0)
.background_color(hex_rgb(0xff_ff_ff))
};
let mut on = Root::new(200.0)
.height(80.0)
.gpu(true)
.children(rounded())
.render(&renderer)
.unwrap_or_else(|error| unreachable!("{error}"));
let mut off = Root::new(200.0)
.height(80.0)
.gpu(false)
.children(rounded())
.render(&renderer)
.unwrap_or_else(|error| unreachable!("{error}"));
let with = on
.to_buffer(Format::Png)
.unwrap_or_else(|error| unreachable!("{error}"));
let without = off
.to_buffer(Format::Png)
.unwrap_or_else(|error| unreachable!("{error}"));
if !cfg!(any(feature = "metal", feature = "vulkan")) {
assert_eq!(
on.engine(),
"cpu",
"no GPU backend is compiled in, so no render can have used one"
);
}
if on.engine() == "gpu" {
assert_ne!(
with, without,
"a GPU device drew one of these, so the two rasterisers should not agree to the byte"
);
} else {
assert_eq!(
with, without,
"no GPU device was used, so both renders are the CPU's and must match"
);
}
}
#[test]
fn a_page_builder_runs_once_per_page() {
let scene =
scene_of(Root::new(10.0).height(10.0).pages(3).page_builder(
|page| Text::new(format!("page {}", page.index)),
));
assert_eq!(scene.pages.len(), 3);
}
#[test]
fn a_duration_becomes_a_page_count_at_the_rate_given() {
let scene = scene_of(
Root::new(10.0)
.height(10.0)
.duration(0.1)
.fps(24.0)
.page_builder(|_| Row::new()),
);
assert_eq!(scene.pages.len(), 3);
}
#[test]
fn a_page_knows_where_it_sits() {
let first = PageInfo::new(0, 4, 10.0);
let last = PageInfo::new(3, 4, 10.0);
assert_eq!(first.progress.to_bits(), 0.0_f32.to_bits());
assert_eq!(last.progress.to_bits(), 1.0_f32.to_bits());
assert_eq!(last.cycle.to_bits(), 0.75_f32.to_bits());
assert_eq!(last.time.to_bits(), 0.3_f32.to_bits());
}
#[test]
fn a_single_page_reports_both_curves_as_zero() {
let only = PageInfo::new(0, 1, 30.0);
assert_eq!(only.progress.to_bits(), 0.0_f32.to_bits());
assert_eq!(only.cycle.to_bits(), 0.0_f32.to_bits());
}
#[test]
fn a_sequence_that_contradicts_itself_is_refused() {
let both = Root::new(10.0)
.height(10.0)
.pages(2)
.duration(1.0)
.page_builder(|_| Row::new())
.into_scene();
let builder_alone = Root::new(10.0)
.height(10.0)
.page_builder(|_| Row::new())
.into_scene();
let length_alone = Root::new(10.0)
.height(10.0)
.pages(2)
.children(Row::new())
.into_scene();
let none = Root::new(10.0)
.height(10.0)
.pages(0)
.page_builder(|_| Row::new())
.into_scene();
assert!(matches!(
both,
Err(BuildError::Sequence(SequenceError::CountAndDuration))
));
assert!(matches!(
builder_alone,
Err(BuildError::Sequence(SequenceError::BuilderWithoutLength))
));
assert!(matches!(
length_alone,
Err(BuildError::Sequence(SequenceError::LengthWithoutBuilder))
));
assert!(matches!(
none,
Err(BuildError::Sequence(SequenceError::NoPages))
));
}
#[test]
fn a_canvas_encodes_twice_from_one_paint() {
let renderer = Renderer::new();
let mut canvas = Root::new(8.0)
.height(4.0)
.background_color(hex_rgb(0x10_10_14))
.render(&renderer)
.unwrap_or_else(|error| unreachable!("{error}"));
let png = canvas
.to_buffer(Format::Png)
.unwrap_or_else(|error| unreachable!("{error}"));
let jpg = canvas
.to_buffer(Format::Jpeg)
.unwrap_or_else(|error| unreachable!("{error}"));
assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n");
assert_eq!(&jpg[..2], b"\xff\xd8");
assert_eq!(canvas.page_count(), 1);
}
#[test]
fn a_filename_names_the_format_it_is_written_in() {
let renderer = Renderer::new();
let mut canvas = Root::new(4.0)
.height(4.0)
.render(&renderer)
.unwrap_or_else(|error| unreachable!("{error}"));
let directory = std::env::temp_dir().join("meo-canvas-to-file");
std::fs::create_dir_all(&directory)
.unwrap_or_else(|error| unreachable!("{error}"));
canvas
.to_file(directory.join("out.png"))
.unwrap_or_else(|error| unreachable!("{error}"));
let written = std::fs::read(directory.join("out.png"))
.unwrap_or_else(|error| unreachable!("{error}"));
assert_eq!(&written[..8], b"\x89PNG\r\n\x1a\n");
assert!(matches!(
canvas.to_file(directory.join("out.nonsense")),
Err(BuildError::Format(_))
));
assert!(matches!(
canvas.to_file(directory.join("out.bin")),
Err(BuildError::Format(_))
));
canvas
.to_file_as(directory.join("out.bin"), Format::Raw)
.unwrap_or_else(|error| unreachable!("{error}"));
}
#[test]
fn a_data_url_carries_the_format_and_the_bytes() {
let renderer = Renderer::new();
let mut canvas = Root::new(4.0)
.height(4.0)
.render(&renderer)
.unwrap_or_else(|error| unreachable!("{error}"));
let url = canvas
.to_url(Format::Png)
.unwrap_or_else(|error| unreachable!("{error}"));
assert!(url.starts_with("data:image/png;base64,"), "{url}");
assert!(url.contains("iVBORw0KGgo"), "{url}");
}
#[test]
fn a_page_root_holds_the_tree_rather_than_wrapping_it() {
let scene =
scene_of(Root::new(10.0).height(10.0).children(
Row::new().children([Text::new("a"), Text::new("b")]),
));
let root = scene
.get(scene.pages[0])
.unwrap_or_else(|| unreachable!("no root"));
let row = scene
.get(root.children[0])
.unwrap_or_else(|| unreachable!("no row"));
assert!(matches!(root.kind, NodeKind::Box));
assert_eq!(row.children.len(), 2);
}
}