Skip to main content

meo_canvas/
root.rs

1//! The entry point, and the canvas a render gives back.
2//!
3//! `Root` is the whole surface's front door: it carries the canvas size, the
4//! renderer's options and the page root's own style, and it is the page root —
5//! its children are the tree. That is the same shape the JavaScript surface
6//! has, deliberately. A person moving between the two should be translating
7//! syntax rather than a design.
8//!
9//! ```
10//! use meo_canvas::{Format, Renderer, Root, Row, Styled, Text, hex, px};
11//!
12//! let renderer = Renderer::new();
13//! let mut canvas = Root::new(520.0)
14//!     .height(180.0)
15//!     .background_color(hex("#101014"))
16//!     .children(Row::new().padding(px(24.0)).children(Text::new("Ukasyah")))
17//!     .render(&renderer)?;
18//!
19//! let png = canvas.to_buffer(Format::Png)?;
20//! # Ok::<(), meo_canvas::BuildError>(())
21//! ```
22//!
23//! **Resolve, measure, layout and paint happen once.** Every method on the
24//! [`Canvas`] that comes back is an encode of work already done, which is why
25//! two formats cost one paint.
26
27use std::{fmt, path::Path};
28
29use meo_canvas_core::{
30    EncodeOptions, Error, ImageFormat, ImageWarning, PreparedEncode,
31    RenderedCanvas, Renderer, diagnostic::Diagnostic,
32};
33use meo_canvas_scene::{
34    OnImageError, Scene, SceneError, Size, node::HttpOptions,
35};
36
37use crate::{
38    ColorSpace, ColorType, Element, IntoElements, Style, Styled,
39    element::write_page,
40};
41
42/// Collects anything acceptable as children.
43fn collect(children: impl IntoElements) -> Vec<Element> {
44    let mut out = Vec::new();
45    children.write_elements(&mut out);
46    out
47}
48
49/// Where one page sits in a sequence.
50///
51/// The four derived numbers rather than the index alone, because each is right
52/// for a different job and deriving the wrong one is a bug that looks like a
53/// design choice.
54#[derive(Debug, Clone, Copy, PartialEq)]
55pub struct PageInfo {
56    /// Zero-based position in the sequence.
57    pub index: u32,
58    /// Total pages in this render.
59    pub count: u32,
60    /// Position along the sequence, `0` on the first page and `1` on the last.
61    ///
62    /// `index / (count - 1)`, which spans the sequence inclusively: a one-shot
63    /// animation should finish at its end value on the frame the viewer stops
64    /// on. The wrong curve for anything that repeats — see
65    /// [`PageInfo::cycle`]. A single-page render reports `0`.
66    pub progress: f32,
67    /// Position around a loop, `0` on the first page and approaching `1`
68    /// without reaching it.
69    ///
70    /// `index / count`, and the one to feed anything periodic. `1` and `0` are
71    /// the same point on a circle, so driving a rotation from
72    /// [`PageInfo::progress`] makes the last page a copy of the first and the
73    /// animation stutters for one frame on every repeat.
74    pub cycle: f32,
75    /// Seconds elapsed at this page, `index / fps`.
76    pub time: f32,
77}
78
79impl PageInfo {
80    /// Where page `index` of `count` sits, at `fps`.
81    fn new(index: u32, count: u32, fps: f32) -> Self {
82        // A single page is the start of its own sequence and the whole of it at
83        // once, so both curves report zero rather than dividing by no interval.
84        let spread = if count > 1 {
85            #[expect(
86                clippy::cast_precision_loss,
87                reason = "a page count large enough to lose precision in an f32 is one no renderer would finish"
88            )]
89            {
90                (index as f32, (count - 1) as f32, count as f32)
91            }
92        } else {
93            (0.0, 1.0, 1.0)
94        };
95        Self {
96            index,
97            count,
98            progress: spread.0 / spread.1,
99            cycle: spread.0 / spread.2,
100            time: spread.0 / fps,
101        }
102    }
103}
104
105/// What went wrong between describing a canvas and painting it.
106#[derive(Debug)]
107#[non_exhaustive]
108pub enum BuildError {
109    /// The pages contradict themselves, or there are none.
110    Sequence(SequenceError),
111    /// The pages do not form a scene the codec can address.
112    Scene(SceneError),
113    /// A pass of the render failed.
114    Render(Error),
115    /// The bytes could not be written to the path given.
116    Write(std::io::Error),
117    /// A filename's extension names no format this can write.
118    Format(String),
119}
120
121impl fmt::Display for BuildError {
122    fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
123        match self {
124            Self::Sequence(error) => error.fmt(out),
125            Self::Scene(error) => error.fmt(out),
126            Self::Render(error) => error.fmt(out),
127            Self::Write(error) => error.fmt(out),
128            Self::Format(path) => write!(
129                out,
130                "cannot tell the format from {path:?}; name the file with an extension such as .png, or use `to_file_as`"
131            ),
132        }
133    }
134}
135
136impl std::error::Error for BuildError {
137    /// The error underneath, so a chain does not stop here: `anyhow`'s `{:#}`,
138    /// `eyre`'s chain and any caller walking `source()` reach the
139    /// `io::ErrorKind` under `Write`, the one thing a caller can act on.
140    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
141        match self {
142            Self::Sequence(error) => Some(error),
143            Self::Scene(error) => Some(error),
144            Self::Render(error) => Some(error),
145            Self::Write(error) => Some(error),
146            // The path is the whole of it; there is nothing underneath.
147            Self::Format(_) => None,
148        }
149    }
150}
151
152impl From<Error> for BuildError {
153    fn from(error: Error) -> Self {
154        Self::Render(error)
155    }
156}
157
158/// A page count that cannot mean what it says.
159///
160/// Refused rather than resolved by precedence. A caller who named both a page
161/// count and a duration, or a count with nothing to vary per page, asked for
162/// something that would not happen.
163#[derive(Debug, Clone, Copy, PartialEq, Eq)]
164#[non_exhaustive]
165pub enum SequenceError {
166    /// Both a page count and a duration were named.
167    CountAndDuration,
168    /// A page builder was set with no count or duration to run it over.
169    BuilderWithoutLength,
170    /// A count or duration was named with no page builder to vary.
171    LengthWithoutBuilder,
172    /// A render has at least one page.
173    NoPages,
174}
175
176impl fmt::Display for SequenceError {
177    fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
178        let said = match self {
179            Self::CountAndDuration => {
180                "name a page count or a duration, not both; they are two spellings of one number"
181            }
182            Self::BuilderWithoutLength => {
183                "a page builder needs `pages` or `duration`; without one there is no sequence to build"
184            }
185            Self::LengthWithoutBuilder => {
186                "`pages` and `duration` describe a sequence, so there has to be a page builder to vary"
187            }
188            Self::NoPages => "a render has at least one page",
189        };
190        out.write_str(said)
191    }
192}
193
194impl std::error::Error for SequenceError {}
195
196/// How the pages of a render are described.
197enum Content {
198    /// One page, holding these children.
199    Fixed(Vec<Element>),
200    /// A page per call, over a sequence whose length is set separately.
201    Built(Box<dyn Fn(PageInfo) -> Vec<Element>>),
202}
203
204impl fmt::Debug for Content {
205    fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result {
206        match self {
207            Self::Fixed(children) => {
208                out.debug_tuple("Fixed").field(children).finish()
209            }
210            Self::Built(_) => out.write_str("Built(<closure>)"),
211        }
212    }
213}
214
215/// The canvas to draw, and the tree to draw on it.
216///
217/// `Root` is the page root as well as the entry point: its style is the page's
218/// style, and its children are the tree. That is why `background_color` here
219/// paints the canvas rather than a box inside it.
220#[derive(Debug)]
221pub struct Root {
222    /// Width in logical pixels.
223    width: f32,
224    /// Height in logical pixels, or the floor when [`Root::content_height`] is
225    /// what set it.
226    height: f32,
227    /// What a render does when an image source cannot be resolved.
228    on_image_error: OnImageError,
229    http: HttpOptions,
230    /// Whether the height comes from the content rather than from the caller.
231    content_height: bool,
232    /// Device-pixel multiplier applied at paint time.
233    scale: f32,
234    /// The page root's own style.
235    style: Style,
236    /// A name carried through for diagnostics.
237    name: Option<String>,
238    /// Whether to rasterise on the GPU, where the caller said.
239    gpu: Option<bool>,
240    /// The pixel layout to composite in, where the caller said.
241    color_type: Option<ColorType>,
242    /// The colour space to composite in, where the caller said.
243    color_space: Option<ColorSpace>,
244    /// What to draw.
245    content: Content,
246    /// How many pages, when a builder describes them.
247    pages: Option<u32>,
248    /// How long the sequence runs, in seconds.
249    duration: Option<f32>,
250    /// The rate a duration and a page's time are derived at.
251    fps: f32,
252}
253
254impl Root {
255    /// The rate a sequence is timed at when nothing says otherwise.
256    pub const DEFAULT_FPS: f32 = 30.0;
257    /// The scale a canvas has when nothing sets one.
258    ///
259    /// One device pixel per logical pixel. Not a judgement about quality: a
260    /// caller rendering for a display multiplies it, and a default above one
261    /// would quadruple the memory of every render that never asked.
262    pub const DEFAULT_SCALE: f32 = 1.0;
263
264    /// A canvas of the given size in logical pixels.
265    ///
266    /// Bare pixels rather than a [`Length`](crate::scene::Length), and
267    /// deliberately: a canvas size is device-independent pixels, and a
268    /// percentage of nothing has no meaning.
269    ///
270    /// **The height is optional and comes from the content when not set**, the
271    /// same as leaving `height` out on the JavaScript surface. Add one with
272    /// [`Root::height`], or a lower bound with [`Root::min_height`].
273    ///
274    /// Rust has no optional argument, and a second constructor taking two
275    /// numbers would make the caller pick a spelling before knowing there was
276    /// a choice. `Root` configures everything else -- scale, name, gpu -- by
277    /// chaining, so the height does too, and the two surfaces then say the
278    /// same thing: a width is required and a height is not.
279    ///
280    /// There is no matching form for the width. Text breaks into lines against
281    /// a width, so a width has to be known before anything can be measured,
282    /// while a height is a result of that measuring.
283    #[must_use]
284    pub const fn new(width: f32) -> Self {
285        Self {
286            width,
287            height: 0.0,
288            content_height: true,
289            scale: Self::DEFAULT_SCALE,
290            on_image_error: OnImageError::Placeholder,
291            http: HttpOptions::new(),
292            // A page lays its children out as flex, and says so: the scene's
293            // default is `block`, which would stack them and stop honouring
294            // `gap` and the alignments. The JavaScript surface's `Box` does
295            // the same.
296            style: Style::new()
297                .display(meo_canvas_scene::style::layout::Display::Flex),
298            name: None,
299            gpu: None,
300            color_type: None,
301            color_space: None,
302            content: Content::Fixed(Vec::new()),
303            pages: None,
304            duration: None,
305            fps: Self::DEFAULT_FPS,
306        }
307    }
308
309    /// Fixes the canvas height, instead of taking it from the content.
310    #[must_use]
311    pub const fn height(mut self, height: f32) -> Self {
312        self.height = height;
313        self.content_height = false;
314        self
315    }
316
317    /// The least the canvas may be while its height comes from its content.
318    ///
319    /// Does nothing once [`Root::height`] has fixed a height: a floor under a
320    /// number that is already stated has nothing to raise.
321    #[must_use]
322    pub const fn min_height(mut self, floor: f32) -> Self {
323        if self.content_height {
324            self.height = floor;
325        }
326        self
327    }
328
329    /// The device-pixel multiplier.
330    ///
331    /// Layout always solves at scale one, so this changes resolution and
332    /// nothing else about where things sit.
333    #[must_use]
334    pub const fn scale(mut self, scale: f32) -> Self {
335        self.scale = scale;
336        self
337    }
338
339    /// A name carried through for diagnostics.
340    ///
341    /// Every page gets it, because every page is this root. The renderer never
342    /// reads it.
343    #[must_use]
344    pub fn name(mut self, name: impl Into<String>) -> Self {
345        self.name = Some(name.into());
346        self
347    }
348
349    /// Rasterise on the GPU when there is one. `false` forces the CPU.
350    ///
351    /// A property of the scene rather than of the [`Renderer`], because the
352    /// canvas is the thing being rasterised — `scale` lives there for the same
353    /// reason. Saying nothing leaves it to the renderer, which is a different
354    /// thing from saying `true`: a renderer someone set to CPU stays there.
355    ///
356    /// Asking is not getting. A build without GPU support, or a driver that
357    /// declines, falls back — and a float [`ColorType`] forces the CPU whatever
358    /// this says, since no GPU composites float. Set it `false` for output that
359    /// must be identical between machines: the two rasterisers resolve
360    /// anti-aliased edges a level or two apart, which a pixel comparison sees.
361    #[must_use]
362    pub const fn gpu(mut self, gpu: bool) -> Self {
363        self.gpu = Some(gpu);
364        self
365    }
366
367    /// What to do when an image source cannot be resolved.
368    ///
369    /// Defaults to [`OnImageError::Placeholder`]: a URL that cannot be fetched
370    /// or decoded draws a neutral mark, and the failure is recorded on
371    /// [`Canvas::warnings`]. The image takes the box Chrome gives a broken
372    /// `<img>` with no `alt` under every setting: an `auto` axis that nothing
373    /// stretches is 16 pixels, and a block-level or stretched one fills its
374    /// container. A
375    /// [`Path`](meo_canvas_scene::node::ImageSource::Path) or
376    /// [`Bytes`](meo_canvas_scene::node::ImageSource::Bytes) source fails the
377    /// render whatever this says -- the caller is holding that input and can
378    /// check it before rendering, where a fetch's outcome does not exist until
379    /// the render runs.
380    ///
381    /// [`OnImageError::Throw`] fails the render instead, for a caller whose
382    /// URLs come from a manifest they control.
383    ///
384    /// **Every setting records the warning.** This chooses what is drawn, not
385    /// what is known.
386    #[must_use]
387    pub const fn on_image_error(mut self, policy: OnImageError) -> Self {
388        self.on_image_error = policy;
389        self
390    }
391
392    /// What every URL in this scene is fetched with.
393    ///
394    /// The same option as npm's `RootProps.httpOptions`: a page pulling twenty
395    /// images from one origin says its credential once rather than twenty
396    /// times. A source's own options merge **over** these,
397    /// one header name at a time, so
398    /// [`Image::url_with`](crate::Image::url_with) at one source does not drop
399    /// what the scene set for the rest.
400    ///
401    /// Only a build with the `net` feature fetches at all; without it a URL is
402    /// [`Error::UnresolvedSource`] and these
403    /// are carried in the scene and never sent.
404    ///
405    /// ```
406    /// use meo_canvas::{Root, scene::HttpOptions};
407    ///
408    /// let root = Root::new(320.0)
409    ///     .height(200.0)
410    ///     .http_options(HttpOptions::new().header("authorization", "Bearer t"));
411    /// ```
412    #[must_use]
413    pub fn http_options(mut self, http: HttpOptions) -> Self {
414        self.http = http;
415        self
416    }
417
418    /// The pixel layout to composite in.
419    ///
420    /// Governs the precision everything is drawn at and the depth the encoded
421    /// formats that carry one write. Saying nothing leaves it to the renderer.
422    #[must_use]
423    pub const fn color_type(mut self, color_type: ColorType) -> Self {
424        self.color_type = Some(color_type);
425        self
426    }
427
428    /// The colour space to composite in.
429    ///
430    /// Fixed for the whole render rather than chosen per export: colours are
431    /// interpreted in it, and one outside its gamut is clipped as it is drawn.
432    /// Saying nothing leaves it to the renderer.
433    #[must_use]
434    pub const fn color_space(mut self, color_space: ColorSpace) -> Self {
435        self.color_space = Some(color_space);
436        self
437    }
438
439    /// The tree to draw, **replacing** anything already set.
440    #[must_use]
441    pub fn children(mut self, children: impl IntoElements) -> Self {
442        self.content = Content::Fixed(collect(children));
443        self
444    }
445
446    /// A tree per page, for a sequence.
447    ///
448    /// Needs [`pages`](Self::pages) or [`duration`](Self::duration) to say how
449    /// long the sequence is. This is where the surfaces differ in syntax and
450    /// not in shape: JavaScript passes a function as `children` because it can,
451    /// and Rust names the two forms apart because it cannot.
452    #[must_use]
453    pub fn page_builder<C: IntoElements>(
454        mut self,
455        builder: impl Fn(PageInfo) -> C + 'static,
456    ) -> Self {
457        self.content =
458            Content::Built(Box::new(move |page| collect(builder(page))));
459        self
460    }
461
462    /// How many pages to render.
463    #[must_use]
464    pub const fn pages(mut self, pages: u32) -> Self {
465        self.pages = Some(pages);
466        self
467    }
468
469    /// How long the sequence runs, in seconds.
470    ///
471    /// The page count becomes `ceil(duration * fps)`.
472    #[must_use]
473    pub const fn duration(mut self, seconds: f32) -> Self {
474        self.duration = Some(seconds);
475        self
476    }
477
478    /// The rate a duration and a page's time are derived at.
479    ///
480    /// Describes the render, not the encode. An animation encoded to play at
481    /// this rate needs it named in [`EncodeOptions`] as well.
482    #[must_use]
483    pub const fn fps(mut self, fps: f32) -> Self {
484        self.fps = fps;
485        self
486    }
487
488    /// How many pages this describes, and at what rate.
489    fn sequence(&self) -> Result<(u32, f32), SequenceError> {
490        let built = matches!(self.content, Content::Built(_));
491
492        if self.pages.is_some() && self.duration.is_some() {
493            return Err(SequenceError::CountAndDuration);
494        }
495
496        #[expect(
497            clippy::cast_possible_truncation,
498            clippy::cast_sign_loss,
499            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"
500        )]
501        let asked = self
502            .pages
503            .or_else(|| self.duration.map(|s| (s * self.fps).ceil() as u32));
504
505        let Some(count) = asked else {
506            if built {
507                return Err(SequenceError::BuilderWithoutLength);
508            }
509            return Ok((1, self.fps));
510        };
511        if !built {
512            return Err(SequenceError::LengthWithoutBuilder);
513        }
514        if count == 0 {
515            return Err(SequenceError::NoPages);
516        }
517        Ok((count, self.fps))
518    }
519
520    /// Flattens this into a scene.
521    ///
522    /// What [`render`](Self::render) hands to the renderer, and public for a
523    /// caller who wants the scene itself — to write to disk, to send over the
524    /// wire, or to render more than once.
525    ///
526    /// # Errors
527    ///
528    /// Returns [`BuildError::Sequence`] when the page count contradicts itself,
529    /// and [`BuildError::Scene`] when the pages together hold more nodes than
530    /// the codec can address.
531    pub fn into_scene(self) -> Result<(Scene, Vec<Diagnostic>), BuildError> {
532        let (count, fps) = self.sequence().map_err(BuildError::Sequence)?;
533
534        // The width came from `Root::new`, which is a `const fn` returning
535        // `Self` and so has nowhere to report a number that is not a length.
536        // This is where it reports: the first call that can fail.
537        let size = Size::new(self.width, self.height);
538        if !meo_canvas_scene::size_is_pixels(size) {
539            return Err(BuildError::Scene(SceneError::canvas_size(
540                self.width,
541                self.height,
542            )));
543        }
544
545        let mut scene = Scene::new(size);
546        scene.content_height = self.content_height;
547        scene.scale = self.scale;
548        scene.gpu = self.gpu;
549        scene.on_image_error = self.on_image_error;
550        scene.http = self.http;
551        scene.color_type = self.color_type;
552        scene.color_space = self.color_space;
553
554        let page_root = |children: Vec<Element>| {
555            let root = Element::new(meo_canvas_scene::node::NodeKind::Box)
556                .with_style(self.style.clone())
557                .children(children);
558            match &self.name {
559                Some(name) => root.name(name.clone()),
560                None => root,
561            }
562        };
563
564        // One list across every page: a caller fixing their markup does not
565        // care which page carried it.
566        let mut found: Vec<Diagnostic> = Vec::new();
567
568        // `Scene::new` already made one page, so the first tree styles it and
569        // every later one adds its own root.
570        let write = |scene: &mut Scene,
571                     first: bool,
572                     children: Vec<Element>,
573                     found: &mut Vec<Diagnostic>|
574         -> Result<(), BuildError> {
575            let root = if first {
576                scene
577                    .root()
578                    .ok_or(BuildError::Sequence(SequenceError::NoPages))?
579            } else {
580                scene.push_page().map_err(BuildError::Scene)?
581            };
582            write_page(scene, root, page_root(children), found)
583                .map_err(BuildError::Scene)
584        };
585
586        match &self.content {
587            Content::Fixed(children) => {
588                write(&mut scene, true, children.clone(), &mut found)?;
589            }
590            Content::Built(builder) => {
591                for index in 0..count {
592                    let children = builder(PageInfo::new(index, count, fps));
593                    write(&mut scene, index == 0, children, &mut found)?;
594                }
595            }
596        }
597        Ok((scene, found))
598    }
599
600    /// Paints every page and returns the canvas to encode from.
601    ///
602    /// The GPU request and the registered families live on the [`Renderer`]
603    /// rather than here: a renderer outlives any one scene, which is why a
604    /// server registers its fonts once, and carrying them in both places would
605    /// be two settings that can disagree. The JavaScript surface, which
606    /// exposes no renderer, puts them on `Root`.
607    ///
608    /// # Errors
609    ///
610    /// Returns whatever [`into_scene`](Self::into_scene) reports, and
611    /// [`BuildError::Render`] when a pass of the render fails — a font the
612    /// renderer does not hold, an image it cannot read, a URL it does not
613    /// fetch.
614    pub fn render(self, renderer: &Renderer) -> Result<Canvas, BuildError> {
615        let (scene, mut diagnostics) = self.into_scene()?;
616        let painted = renderer.render(&scene)?;
617        diagnostics.extend_from_slice(painted.diagnostics());
618        Ok(Canvas {
619            painted,
620            diagnostics,
621        })
622    }
623}
624
625impl Styled for Root {
626    fn style_mut(&mut self) -> &mut Style {
627        &mut self.style
628    }
629}
630
631/// A painted canvas, and the ways to read it back.
632///
633/// Returned by [`Root::render`]; a caller never builds one. It holds the
634/// painted surface and nothing else, so every method here is an encode of work
635/// already done.
636///
637/// The binding is `mut` because encoding takes `&mut self` — every encode entry
638/// point in the renderer beneath does, since writing a format prepares the page
639/// sequence first. A signature hiding that behind interior mutability would let
640/// two encodes read as independent when they are not.
641#[derive(Debug)]
642pub struct Canvas {
643    /// The painted pages.
644    painted: RenderedCanvas,
645    /// What the caller wrote that could not be used: markup, raised while the
646    /// scene was built, then a filter chain the render dropped. A caller who
647    /// builds the scene takes the first from [`Root::into_scene`] and the
648    /// second from `RenderedCanvas::diagnostics`.
649    diagnostics: Vec<Diagnostic>,
650}
651
652impl Canvas {
653    /// What this render's input said that could not be used: a markup tag, or
654    /// a `filter` or `backdrop_filter` chain the renderer refuses, which is
655    /// drawn as though it were not set.
656    ///
657    /// **Separate from an image warning**, which reports that the world did
658    /// not answer. A diagnostic reports that the input did not say what it
659    /// meant, which is the caller's to fix rather than the network's.
660    #[must_use]
661    pub fn diagnostics(&self) -> &[Diagnostic] {
662        &self.diagnostics
663    }
664
665    /// Encodes the canvas and returns the bytes.
666    ///
667    /// # Errors
668    ///
669    /// Returns [`BuildError::Render`] when the encoder refuses the surface.
670    pub fn to_buffer(
671        &mut self,
672        format: ImageFormat,
673    ) -> Result<Vec<u8>, BuildError> {
674        self.to_buffer_with(format, &EncodeOptions::default())
675    }
676
677    /// Encodes the canvas with quality and container settings.
678    ///
679    /// # Errors
680    ///
681    /// Returns [`BuildError::Render`] when the encoder refuses the surface or
682    /// the options do not fit the painted pages.
683    pub fn to_buffer_with(
684        &mut self,
685        format: ImageFormat,
686        options: &EncodeOptions,
687    ) -> Result<Vec<u8>, BuildError> {
688        Ok(self.painted.to_buffer(format, options)?)
689    }
690
691    /// Takes the half of an encode that needs this canvas, and stops there.
692    ///
693    /// The returned [`PreparedEncode`] is [`Send`] where this canvas is not,
694    /// so the expensive half of an export runs wherever the caller puts it
695    /// while this canvas stays on the thread that owns it. At 4000x4000 that
696    /// is 97 ms of the 100 a `to_buffer` costs.
697    ///
698    /// The JavaScript surface's `toBuffer` settles off the event loop for the
699    /// same reason a caller serving requests from a thread pool wants this.
700    ///
701    /// One handle is one format: encoding a second format is a second call,
702    /// made here rather than on the worker.
703    ///
704    /// ```
705    /// use meo_canvas::{EncodeOptions, Format, Renderer, Root};
706    ///
707    /// let renderer = Renderer::new();
708    /// let mut canvas = Root::new(64.0).height(32.0).render(&renderer)?;
709    ///
710    /// let pending =
711    ///     canvas.prepare_encode(Format::Png, &EncodeOptions::default())?;
712    /// let png = std::thread::spawn(move || pending.encode())
713    ///     .join()
714    ///     .expect("the encoding thread")?;
715    /// assert!(!png.bytes.is_empty());
716    /// # Ok::<(), meo_canvas::BuildError>(())
717    /// ```
718    ///
719    /// # Errors
720    ///
721    /// Returns [`BuildError::Render`] when the options do not fit the painted
722    /// pages. Failures that belong to encoding itself are raised by
723    /// [`PreparedEncode::encode`].
724    pub fn prepare_encode(
725        &mut self,
726        format: ImageFormat,
727        options: &EncodeOptions,
728    ) -> Result<PreparedEncode, BuildError> {
729        Ok(self.painted.prepare_encode(format, options)?)
730    }
731
732    /// Encodes the canvas and writes it to `path`, taking the format from the
733    /// extension.
734    ///
735    /// `canvas.to_file("out.png")`, the same call a JavaScript caller writes,
736    /// and it accepts the same extensions — `.raw` among them. An extension
737    /// naming no format is an error rather than a default: writing a PNG
738    /// because nothing said otherwise turns a typo into a file whose name lies
739    /// about its contents.
740    ///
741    /// Resolved through [`ImageFormat::from_named`] rather than
742    /// `from_extension`, which refuses `raw` — correctly, for a filename found
743    /// on disk, and wrongly for one the caller has just typed.
744    ///
745    /// # Errors
746    ///
747    /// Returns [`BuildError::Format`] when the extension names no format, and
748    /// [`BuildError::Render`] or [`BuildError::Write`] when the encode or the
749    /// write fails.
750    pub fn to_file(
751        &mut self,
752        path: impl AsRef<Path>,
753    ) -> Result<(), BuildError> {
754        let path = path.as_ref();
755        let format = path
756            .extension()
757            .and_then(|extension| extension.to_str())
758            .and_then(ImageFormat::from_named)
759            .ok_or_else(|| BuildError::Format(path.display().to_string()))?;
760        self.to_file_with(path, format, &EncodeOptions::default())
761    }
762
763    /// Encodes the canvas in the named format and writes it to `path`.
764    ///
765    /// # Errors
766    ///
767    /// As [`Canvas::to_file_with`], whose notes on the two error variants
768    /// apply here too.
769    pub fn to_file_as(
770        &mut self,
771        path: impl AsRef<Path>,
772        format: ImageFormat,
773    ) -> Result<(), BuildError> {
774        self.to_file_with(path, format, &EncodeOptions::default())
775    }
776
777    /// Encodes the canvas with options and writes it to `path`.
778    ///
779    /// **The bytes are written where they are encoded**: a format that gathers
780    /// every page streams into the file rather than existing whole in memory
781    /// first.
782    ///
783    /// # Why the path is opened before the encode
784    ///
785    /// So a path that cannot be written is still [`BuildError::Write`] with
786    /// its [`std::io::ErrorKind`] intact — a missing directory, a permission
787    /// refusal, a read-only filesystem. The renderer folds a write failure
788    /// into an encode error carrying a message rather than a kind, and the
789    /// kind is what a caller can act on. It also fails sooner. A failure
790    /// *during* the write — a full disk — still arrives as
791    /// [`BuildError::Render`].
792    ///
793    /// # Why the probe neither truncates nor leaves a file behind
794    ///
795    /// **A failed encode must not destroy the file already there.** An
796    /// existing path is opened for writing without truncating; truncation
797    /// happens in the renderer, on the success path. A path that does not
798    /// exist is created with `create_new` and removed again, so a failed encode
799    /// leaves nothing. That removal's error is the one swallowed here: it can
800    /// only leave behind the empty file this call has just created.
801    ///
802    /// # Errors
803    ///
804    /// Returns [`BuildError::Write`] when the path cannot be opened for
805    /// writing, and [`BuildError::Render`] when the options do not suit the
806    /// format, when the encoder refuses the surface, or when the write fails
807    /// after it has begun.
808    pub fn to_file_with(
809        &mut self,
810        path: impl AsRef<Path>,
811        format: ImageFormat,
812        options: &EncodeOptions,
813    ) -> Result<(), BuildError> {
814        let path = path.as_ref();
815        // Opened and dropped, not written through: the renderer opens the path
816        // itself. This is here to ask the filesystem the question while the
817        // answer is still an `io::Error`. See the notes above for why it does
818        // not truncate and why it cleans up after itself.
819        match std::fs::OpenOptions::new()
820            .write(true)
821            .create_new(true)
822            .open(path)
823        {
824            Ok(file) => {
825                drop(file);
826                drop(std::fs::remove_file(path));
827            }
828            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
829                drop(
830                    std::fs::OpenOptions::new()
831                        .write(true)
832                        .open(path)
833                        .map_err(BuildError::Write)?,
834                );
835            }
836            Err(error) => return Err(BuildError::Write(error)),
837        }
838        Ok(self.painted.prepare_encode(format, options)?.write(path)?)
839    }
840
841    /// Encodes the canvas and returns a `data:` URL.
842    ///
843    /// # Errors
844    ///
845    /// Returns [`BuildError::Render`] when the encoder refuses the surface.
846    pub fn to_url(
847        &mut self,
848        format: ImageFormat,
849    ) -> Result<String, BuildError> {
850        let bytes = self.to_buffer(format)?;
851        Ok(format!(
852            "data:{};base64,{}",
853            format.media_type(),
854            base64(&bytes)
855        ))
856    }
857
858    /// The `HTMLCanvasElement` spelling of [`to_url`](Self::to_url).
859    ///
860    /// Taking a quality rather than an options object, because the DOM method
861    /// it is named after does.
862    ///
863    /// # Errors
864    ///
865    /// Returns [`BuildError::Render`] when the encoder refuses the surface.
866    pub fn to_data_url(
867        &mut self,
868        format: ImageFormat,
869        quality: Option<f32>,
870    ) -> Result<String, BuildError> {
871        let options = EncodeOptions {
872            quality,
873            ..EncodeOptions::default()
874        };
875        let bytes = self.to_buffer_with(format, &options)?;
876        Ok(format!(
877            "data:{};base64,{}",
878            format.media_type(),
879            base64(&bytes)
880        ))
881    }
882
883    /// How many pages were painted.
884    #[must_use]
885    pub fn page_count(&self) -> usize {
886        self.painted.page_count()
887    }
888
889    /// The device-pixel multiplier the pages were drawn at.
890    #[must_use]
891    pub const fn scale(&self) -> f32 {
892        self.painted.scale()
893    }
894
895    /// Every image source that could not be resolved, in node order.
896    ///
897    /// **Empty is the ordinary answer and always safe to ask for**, so
898    /// `warnings().is_empty()` needs no guard. One entry per distinct source
899    /// rather than per node.
900    ///
901    /// Populated whatever [`Root::on_image_error`] chose, including
902    /// [`OnImageError::Ignore`]: a caller who finds the mark distracting keeps
903    /// the diagnostic, because turning the drawing off must not turn the
904    /// knowing off.
905    #[must_use]
906    pub fn warnings(&self) -> &[ImageWarning] {
907        self.painted.warnings()
908    }
909
910    /// Whether the GPU was asked for.
911    ///
912    /// **Asking is not getting** -- compare [`Canvas::engine`]. This is what
913    /// [`Root::gpu`] was told, and it is `true` when nothing was said, because
914    /// that is the renderer's own default.
915    #[must_use]
916    pub const fn gpu(&self) -> bool {
917        self.painted.gpu()
918    }
919
920    /// Which rasteriser drew the pages: `"gpu"` or `"cpu"`.
921    ///
922    /// The outcome rather than the request, and they disagree: a build with no
923    /// GPU backend compiled, a machine with no device, a driver that declines,
924    /// and a float `color_type` all rasterise on the CPU whatever `gpu` says.
925    /// **Without this a caller who asks for the GPU and gets the CPU has no way
926    /// to find out**, and neither has a test. The JavaScript surface's canvas
927    /// reports the same.
928    #[must_use]
929    pub fn engine(&self) -> &'static str {
930        self.painted.engine()
931    }
932}
933
934/// Base64, for a `data:` URL.
935fn base64(bytes: &[u8]) -> String {
936    const ALPHABET: &[u8; 64] =
937        b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
938
939    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
940    for chunk in bytes.chunks(3) {
941        let (a, b, c) = (
942            u32::from(chunk[0]),
943            chunk.get(1).map_or(0, |byte| u32::from(*byte)),
944            chunk.get(2).map_or(0, |byte| u32::from(*byte)),
945        );
946        let triple = (a << 16) | (b << 8) | c;
947
948        out.push(ALPHABET[((triple >> 18) & 63) as usize] as char);
949        out.push(ALPHABET[((triple >> 12) & 63) as usize] as char);
950        out.push(if chunk.len() > 1 {
951            ALPHABET[((triple >> 6) & 63) as usize] as char
952        } else {
953            '='
954        });
955        out.push(if chunk.len() > 2 {
956            ALPHABET[(triple & 63) as usize] as char
957        } else {
958            '='
959        });
960    }
961    out
962}
963
964#[cfg(test)]
965mod tests {
966    use meo_canvas_scene::node::NodeKind;
967
968    use super::{BuildError, PageInfo, Root, SequenceError};
969    use crate::{
970        Box, ColorSpace, ColorType, Column, EncodeOptions, Format, Renderer,
971        Row, Styled, Text, hex_rgb, px,
972    };
973
974    #[test]
975    fn a_build_error_hands_back_what_went_wrong_underneath_it() {
976        // `source()` must reach the `io::ErrorKind` under `Write`: `Display`
977        // forwards, so the message looks complete whether or not the chain is.
978        use std::error::Error as _;
979
980        let refused = Root::new(f32::NAN)
981            .children([Box::new()])
982            .into_scene()
983            .err()
984            .unwrap_or_else(|| unreachable!("a NaN width is refused"));
985        let source = refused
986            .source()
987            .unwrap_or_else(|| unreachable!("the scene error is underneath"));
988        assert!(
989            source
990                .downcast_ref::<meo_canvas_scene::SceneError>()
991                .is_some(),
992            "the cause came back as something other than the scene error"
993        );
994
995        // The `io::Error` case, which is the one worth reaching: a caller
996        // deciding whether to retry needs the kind, not the sentence.
997        let io = BuildError::Write(std::io::Error::new(
998            std::io::ErrorKind::PermissionDenied,
999            "no",
1000        ));
1001        let kind = io
1002            .source()
1003            .and_then(|error| error.downcast_ref::<std::io::Error>())
1004            .map(std::io::Error::kind);
1005        assert_eq!(kind, Some(std::io::ErrorKind::PermissionDenied));
1006    }
1007
1008    #[test]
1009    fn a_written_file_is_the_buffer_and_a_bad_path_keeps_its_error_kind() {
1010        use std::error::Error as _;
1011
1012        // Two claims about `to_file_with`, and the second is why it is not
1013        // simply `prepare_encode(..).write(..)`. The first: streaming writes
1014        // the same file buffering does, byte for byte.
1015        let renderer = Renderer::new();
1016        let mut canvas = Root::new(16.0)
1017            .height(8.0)
1018            .render(&renderer)
1019            .unwrap_or_else(|error| unreachable!("{error}"));
1020        let expected = canvas
1021            .to_buffer(Format::Png)
1022            .unwrap_or_else(|error| unreachable!("{error}"));
1023
1024        let path = std::env::temp_dir().join("meo-canvas-root-to-file.png");
1025        canvas
1026            .to_file(&path)
1027            .unwrap_or_else(|error| unreachable!("{error}"));
1028        let written = std::fs::read(&path)
1029            .unwrap_or_else(|error| unreachable!("{error}"));
1030        assert_eq!(written, expected, "the file and the buffer differ");
1031        std::fs::remove_file(&path)
1032            .unwrap_or_else(|error| unreachable!("{error}"));
1033
1034        // The second: a path that cannot be opened is still a `Write` with a
1035        // real `io::ErrorKind` under it. Without the file created before the
1036        // encode, the renderer's sentence-carrying error would arrive as
1037        // `Render` and the kind would be gone.
1038        let missing = std::env::temp_dir()
1039            .join("meo-canvas-no-such-directory")
1040            .join("out.png");
1041        let refused = canvas.to_file(&missing);
1042        let Err(error) = refused else {
1043            unreachable!("writing into a missing directory succeeded");
1044        };
1045        assert!(
1046            matches!(error, BuildError::Write(_)),
1047            "a missing directory reported {error:?} rather than a write error"
1048        );
1049        let kind = error
1050            .source()
1051            .and_then(|cause| cause.downcast_ref::<std::io::Error>())
1052            .map(std::io::Error::kind);
1053        assert_eq!(kind, Some(std::io::ErrorKind::NotFound));
1054    }
1055
1056    #[test]
1057    fn a_refused_encode_leaves_the_previous_file_alone() {
1058        // The failure the probe must not cause: `File::create` truncates, so
1059        // probing with it would empty the path before an encode refused for an
1060        // ordinary reason -- `fps` on a still format -- and leave yesterday's
1061        // render a zero-byte file.
1062        let renderer = Renderer::new();
1063        let mut canvas = Root::new(16.0)
1064            .height(8.0)
1065            .render(&renderer)
1066            .unwrap_or_else(|error| unreachable!("{error}"));
1067
1068        let path = std::env::temp_dir().join("meo-canvas-not-clobbered.png");
1069        canvas
1070            .to_file(&path)
1071            .unwrap_or_else(|error| unreachable!("{error}"));
1072        let before = std::fs::read(&path)
1073            .unwrap_or_else(|error| unreachable!("{error}"));
1074        assert!(!before.is_empty(), "the first write produced nothing");
1075
1076        // A frame rate means nothing to a PNG, which `EncodeOptions::validate`
1077        // refuses before anything is drawn.
1078        let refused = canvas.to_file_with(
1079            &path,
1080            Format::Png,
1081            &EncodeOptions {
1082                fps: Some(30.0),
1083                ..EncodeOptions::default()
1084            },
1085        );
1086        assert!(refused.is_err(), "a frame rate on a PNG was accepted");
1087
1088        let after = std::fs::read(&path)
1089            .unwrap_or_else(|error| unreachable!("{error}"));
1090        assert_eq!(
1091            after, before,
1092            "a refused encode changed the file that was already there"
1093        );
1094        std::fs::remove_file(&path)
1095            .unwrap_or_else(|error| unreachable!("{error}"));
1096    }
1097
1098    #[test]
1099    fn a_refused_encode_leaves_no_file_where_there_was_none() {
1100        // The other half: the probe creates a path that does not exist, so it
1101        // has to remove it again. Left behind, a refused encode would put a
1102        // zero-byte file where it used to put nothing at all.
1103        let renderer = Renderer::new();
1104        let mut canvas = Root::new(16.0)
1105            .height(8.0)
1106            .render(&renderer)
1107            .unwrap_or_else(|error| unreachable!("{error}"));
1108
1109        let path = std::env::temp_dir().join("meo-canvas-no-residue.png");
1110        drop(std::fs::remove_file(&path));
1111
1112        let refused = canvas.to_file_with(
1113            &path,
1114            Format::Png,
1115            &EncodeOptions {
1116                fps: Some(30.0),
1117                ..EncodeOptions::default()
1118            },
1119        );
1120        assert!(refused.is_err(), "a frame rate on a PNG was accepted");
1121        assert!(
1122            !path.exists(),
1123            "a refused encode left a file at a path that had none"
1124        );
1125    }
1126
1127    #[test]
1128    fn a_root_whose_width_is_not_a_length_is_refused() {
1129        // `Root::new` is a `const fn` returning `Self`, so it has nowhere to
1130        // report a width that is not a number of pixels. `into_scene` is the
1131        // first call that can, and until 5 September 2026 it did not: a root
1132        // of `NaN` built a scene sized `NaN by 0.0` and rendered nothing.
1133        for width in [f32::NAN, -100.0, f32::INFINITY] {
1134            let refused = Root::new(width).children([Box::new()]).into_scene();
1135            assert!(
1136                matches!(
1137                    refused,
1138                    Err(BuildError::Scene(
1139                        meo_canvas_scene::SceneError::CanvasSize { .. }
1140                    ))
1141                ),
1142                "a width of {width} was accepted"
1143            );
1144        }
1145
1146        // A height set explicitly reaches the same check.
1147        let refused = Root::new(10.0)
1148            .height(-1.0)
1149            .children([Box::new()])
1150            .into_scene();
1151        assert!(matches!(
1152            refused,
1153            Err(BuildError::Scene(
1154                meo_canvas_scene::SceneError::CanvasSize { .. }
1155            ))
1156        ));
1157
1158        // And zero stays a canvas, as it is on the element surface.
1159        assert!(Root::new(0.0).children([Box::new()]).into_scene().is_ok());
1160    }
1161
1162    #[test]
1163    fn to_file_accepts_the_extensions_the_javascript_surface_does() {
1164        // `.raw` among them. `ImageFormat::from_extension` refuses it, rightly
1165        // for a filename found on disk -- a `.bin` of pixel bytes implies no
1166        // format -- but a path the caller has just typed is the other question.
1167        let dir = std::env::temp_dir()
1168            .join(format!("meo-to-file-{}", std::process::id()));
1169        std::fs::create_dir_all(&dir)
1170            .unwrap_or_else(|error| unreachable!("{error}"));
1171
1172        let mut canvas = Root::new(8.0)
1173            .height(4.0)
1174            .children(Box::new())
1175            .render(&Renderer::new())
1176            .unwrap_or_else(|error| unreachable!("{error}"));
1177
1178        for extension in ["png", "raw", "RAW"] {
1179            let path = dir.join(format!("out.{extension}"));
1180            assert!(
1181                canvas.to_file(&path).is_ok(),
1182                ".{extension} should name a format"
1183            );
1184        }
1185        // Eight by four at four bytes a pixel, so the bytes are the pixels and
1186        // nothing else -- which is the whole of what `raw` promises.
1187        assert_eq!(
1188            std::fs::metadata(dir.join("out.raw"))
1189                .unwrap_or_else(|error| unreachable!("{error}"))
1190                .len(),
1191            8 * 4 * 4
1192        );
1193
1194        // `.bin` is upstream's name for the container and not a format tag, so
1195        // neither surface takes it. Refusing it here is the parity, not a gap.
1196        for extension in ["bin", "nonsense"] {
1197            let path = dir.join(format!("out.{extension}"));
1198            assert!(
1199                matches!(canvas.to_file(&path), Err(BuildError::Format(_))),
1200                ".{extension} names no format"
1201            );
1202        }
1203
1204        std::fs::remove_dir_all(&dir).ok();
1205    }
1206
1207    /// The scene `root` describes, or the failure it reports.
1208    fn scene_of(root: Root) -> meo_canvas_scene::Scene {
1209        root.into_scene()
1210            .map_or_else(|error| unreachable!("{error}"), |(scene, _)| scene)
1211    }
1212
1213    #[test]
1214    fn a_root_takes_its_size_and_defaults_the_scale() {
1215        let scene = scene_of(Root::new(120.0).height(60.0));
1216
1217        assert_eq!(scene.size.width.to_bits(), 120.0_f32.to_bits());
1218        assert_eq!(scene.size.height.to_bits(), 60.0_f32.to_bits());
1219        assert_eq!(scene.scale.to_bits(), Root::DEFAULT_SCALE.to_bits());
1220    }
1221
1222    #[test]
1223    fn the_scale_reaches_the_scene_without_moving_the_layout() {
1224        // Layout always solves at one, so this changes resolution and nothing
1225        // about where things sit.
1226        let scene = scene_of(Root::new(10.0).height(10.0).scale(3.0));
1227
1228        assert_eq!(scene.scale.to_bits(), 3.0_f32.to_bits());
1229    }
1230
1231    #[test]
1232    fn the_root_is_the_page_rather_than_a_box_inside_it() {
1233        // `background_color` on `Root` paints the canvas. A wrapper node would
1234        // paint a box the size of the content instead, which is the bug this
1235        // shape exists to make impossible.
1236        let scene = scene_of(
1237            Root::new(10.0)
1238                .height(10.0)
1239                .background_color(hex_rgb(0x10_10_14))
1240                .children(Row::new()),
1241        );
1242        let root = scene
1243            .get(scene.pages[0])
1244            .unwrap_or_else(|| unreachable!("the scene has no root"));
1245
1246        assert_eq!(root.paint.background_color, hex_rgb(0x10_10_14).into());
1247        assert_eq!(root.children.len(), 1);
1248    }
1249
1250    #[test]
1251    fn children_take_one_or_many_and_skip_what_did_not_render() {
1252        let one = scene_of(Root::new(10.0).height(10.0).children(Row::new()));
1253        let many = scene_of(
1254            Root::new(10.0)
1255                .height(10.0)
1256                .children([Row::new(), Column::new()]),
1257        );
1258        let conditional = scene_of(Root::new(10.0).height(10.0).children([
1259            Some(Row::new()),
1260            None,
1261            Some(Column::new()),
1262        ]));
1263
1264        let count = |scene: &meo_canvas_scene::Scene| {
1265            scene
1266                .get(scene.pages[0])
1267                .map_or(0, |root| root.children.len())
1268        };
1269        assert_eq!(count(&one), 1);
1270        assert_eq!(count(&many), 2);
1271        // The `None` contributes nothing rather than an empty node, which is
1272        // what `cond && Text(…)` means on the other surface.
1273        assert_eq!(count(&conditional), 2);
1274    }
1275
1276    #[test]
1277    fn a_flat_setter_writes_the_same_field_the_style_does() {
1278        // The trait's whole claim: one list of properties, two places they can
1279        // be written, and no chance of the two drifting apart.
1280        let scene =
1281            scene_of(Root::new(10.0).height(10.0).children(
1282                Row::new().gap(px(4.0)).padding(crate::all(px(8.0))),
1283            ));
1284        let root = scene
1285            .get(scene.pages[0])
1286            .unwrap_or_else(|| unreachable!("the scene has no root"));
1287        let child = scene
1288            .get(root.children[0])
1289            .unwrap_or_else(|| unreachable!("the root has no child"));
1290
1291        assert_eq!(child.layout.gap.0, meo_canvas_scene::Length::Points(4.0));
1292        assert_eq!(
1293            child.layout.padding.top,
1294            meo_canvas_scene::Length::Points(8.0)
1295        );
1296    }
1297
1298    #[test]
1299    fn a_name_reaches_the_node_it_was_written_on() {
1300        // Not a style property: the scene keeps it on the node beside the kind
1301        // and nothing inherits it, so it does not go through `properties!`.
1302        let scene = scene_of(
1303            Root::new(10.0)
1304                .height(10.0)
1305                .name("page")
1306                .children(Row::new().name("card")),
1307        );
1308        let root = scene
1309            .get(scene.pages[0])
1310            .unwrap_or_else(|| unreachable!("the scene has no root"));
1311        let child = scene
1312            .get(root.children[0])
1313            .unwrap_or_else(|| unreachable!("the root has no child"));
1314
1315        assert_eq!(root.name.as_deref(), Some("page"));
1316        assert_eq!(child.name.as_deref(), Some("card"));
1317    }
1318
1319    #[test]
1320    fn a_name_is_absent_when_none_was_given() {
1321        let scene = scene_of(Root::new(10.0).height(10.0).children(Row::new()));
1322        let root = scene
1323            .get(scene.pages[0])
1324            .unwrap_or_else(|| unreachable!("the scene has no root"));
1325
1326        assert_eq!(root.name, None);
1327    }
1328
1329    #[test]
1330    fn the_surface_options_reach_the_scene_and_stay_absent_otherwise() {
1331        // Absent is not `false`: the renderer decides when the caller said
1332        // nothing, and a default written here would take that decision away
1333        // from a renderer someone deliberately set to CPU.
1334        let silent = scene_of(Root::new(10.0).height(10.0));
1335        let stated = scene_of(
1336            Root::new(10.0)
1337                .height(10.0)
1338                .gpu(false)
1339                .color_type(ColorType::F32)
1340                .color_space(ColorSpace::DisplayP3),
1341        );
1342
1343        assert_eq!(silent.gpu, None);
1344        assert_eq!(silent.color_type, None);
1345        assert_eq!(silent.color_space, None);
1346        assert_eq!(stated.gpu, Some(false));
1347        assert_eq!(stated.color_type, Some(ColorType::F32));
1348        assert_eq!(stated.color_space, Some(ColorSpace::DisplayP3));
1349    }
1350
1351    #[test]
1352    fn the_two_rasterisers_do_not_draw_the_same_pixels() {
1353        // Two real renders that must differ, which a copied flag cannot fake.
1354        // Text is load-bearing: the rasterisers differ only on anti-aliased
1355        // edges, so a plain filled box would fail this. With no GPU compiled
1356        // in, both are the CPU and the test says so.
1357        let renderer = Renderer::new();
1358        let rounded = || {
1359            Box::new()
1360                .size(px(120.0), px(60.0))
1361                .border_radius(24.0)
1362                .background_color(hex_rgb(0xff_ff_ff))
1363        };
1364
1365        let mut on = Root::new(200.0)
1366            .height(80.0)
1367            .gpu(true)
1368            .children(rounded())
1369            .render(&renderer)
1370            .unwrap_or_else(|error| unreachable!("{error}"));
1371        let mut off = Root::new(200.0)
1372            .height(80.0)
1373            .gpu(false)
1374            .children(rounded())
1375            .render(&renderer)
1376            .unwrap_or_else(|error| unreachable!("{error}"));
1377
1378        let with = on
1379            .to_buffer(Format::Png)
1380            .unwrap_or_else(|error| unreachable!("{error}"));
1381        let without = off
1382            .to_buffer(Format::Png)
1383            .unwrap_or_else(|error| unreachable!("{error}"));
1384
1385        // Branch on the engine that drew, not the backend compiled in: a
1386        // headless runner compiles Vulkan, finds no device and falls back, so
1387        // both renders are the CPU's. There the GPU path is not verified, and
1388        // the `else` arm asserts only a clean fallback.
1389        if !cfg!(any(feature = "metal", feature = "vulkan")) {
1390            assert_eq!(
1391                on.engine(),
1392                "cpu",
1393                "no GPU backend is compiled in, so no render can have used one"
1394            );
1395        }
1396        if on.engine() == "gpu" {
1397            assert_ne!(
1398                with, without,
1399                "a GPU device drew one of these, so the two rasterisers should not agree to the byte"
1400            );
1401        } else {
1402            assert_eq!(
1403                with, without,
1404                "no GPU device was used, so both renders are the CPU's and must match"
1405            );
1406        }
1407    }
1408
1409    #[test]
1410    fn a_page_builder_runs_once_per_page() {
1411        let scene =
1412            scene_of(Root::new(10.0).height(10.0).pages(3).page_builder(
1413                |page| Text::new(format!("page {}", page.index)),
1414            ));
1415
1416        assert_eq!(scene.pages.len(), 3);
1417    }
1418
1419    #[test]
1420    fn a_duration_becomes_a_page_count_at_the_rate_given() {
1421        // `ceil(duration * fps)`: a fraction of a page is still a page that
1422        // has to be drawn.
1423        let scene = scene_of(
1424            Root::new(10.0)
1425                .height(10.0)
1426                .duration(0.1)
1427                .fps(24.0)
1428                .page_builder(|_| Row::new()),
1429        );
1430
1431        assert_eq!(scene.pages.len(), 3);
1432    }
1433
1434    #[test]
1435    fn a_page_knows_where_it_sits() {
1436        let first = PageInfo::new(0, 4, 10.0);
1437        let last = PageInfo::new(3, 4, 10.0);
1438
1439        // `progress` reaches one on the last page; `cycle` never does, because
1440        // the page after the last is the next loop's first.
1441        assert_eq!(first.progress.to_bits(), 0.0_f32.to_bits());
1442        assert_eq!(last.progress.to_bits(), 1.0_f32.to_bits());
1443        assert_eq!(last.cycle.to_bits(), 0.75_f32.to_bits());
1444        assert_eq!(last.time.to_bits(), 0.3_f32.to_bits());
1445    }
1446
1447    #[test]
1448    fn a_single_page_reports_both_curves_as_zero() {
1449        let only = PageInfo::new(0, 1, 30.0);
1450
1451        assert_eq!(only.progress.to_bits(), 0.0_f32.to_bits());
1452        assert_eq!(only.cycle.to_bits(), 0.0_f32.to_bits());
1453    }
1454
1455    #[test]
1456    fn a_sequence_that_contradicts_itself_is_refused() {
1457        let both = Root::new(10.0)
1458            .height(10.0)
1459            .pages(2)
1460            .duration(1.0)
1461            .page_builder(|_| Row::new())
1462            .into_scene();
1463        let builder_alone = Root::new(10.0)
1464            .height(10.0)
1465            .page_builder(|_| Row::new())
1466            .into_scene();
1467        let length_alone = Root::new(10.0)
1468            .height(10.0)
1469            .pages(2)
1470            .children(Row::new())
1471            .into_scene();
1472        let none = Root::new(10.0)
1473            .height(10.0)
1474            .pages(0)
1475            .page_builder(|_| Row::new())
1476            .into_scene();
1477
1478        assert!(matches!(
1479            both,
1480            Err(BuildError::Sequence(SequenceError::CountAndDuration))
1481        ));
1482        assert!(matches!(
1483            builder_alone,
1484            Err(BuildError::Sequence(SequenceError::BuilderWithoutLength))
1485        ));
1486        assert!(matches!(
1487            length_alone,
1488            Err(BuildError::Sequence(SequenceError::LengthWithoutBuilder))
1489        ));
1490        assert!(matches!(
1491            none,
1492            Err(BuildError::Sequence(SequenceError::NoPages))
1493        ));
1494    }
1495
1496    #[test]
1497    fn a_canvas_encodes_twice_from_one_paint() {
1498        let renderer = Renderer::new();
1499        let mut canvas = Root::new(8.0)
1500            .height(4.0)
1501            .background_color(hex_rgb(0x10_10_14))
1502            .render(&renderer)
1503            .unwrap_or_else(|error| unreachable!("{error}"));
1504
1505        let png = canvas
1506            .to_buffer(Format::Png)
1507            .unwrap_or_else(|error| unreachable!("{error}"));
1508        let jpg = canvas
1509            .to_buffer(Format::Jpeg)
1510            .unwrap_or_else(|error| unreachable!("{error}"));
1511
1512        assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n");
1513        assert_eq!(&jpg[..2], b"\xff\xd8");
1514        assert_eq!(canvas.page_count(), 1);
1515    }
1516
1517    #[test]
1518    fn a_filename_names_the_format_it_is_written_in() {
1519        // The same call a JavaScript caller writes,
1520        // `canvas.to_file("out.png")`. An extension naming no format is
1521        // refused rather than defaulted: a typo would otherwise produce
1522        // a file whose name lies about its contents.
1523        let renderer = Renderer::new();
1524        let mut canvas = Root::new(4.0)
1525            .height(4.0)
1526            .render(&renderer)
1527            .unwrap_or_else(|error| unreachable!("{error}"));
1528
1529        let directory = std::env::temp_dir().join("meo-canvas-to-file");
1530        std::fs::create_dir_all(&directory)
1531            .unwrap_or_else(|error| unreachable!("{error}"));
1532
1533        canvas
1534            .to_file(directory.join("out.png"))
1535            .unwrap_or_else(|error| unreachable!("{error}"));
1536        let written = std::fs::read(directory.join("out.png"))
1537            .unwrap_or_else(|error| unreachable!("{error}"));
1538
1539        assert_eq!(&written[..8], b"\x89PNG\r\n\x1a\n");
1540        assert!(matches!(
1541            canvas.to_file(directory.join("out.nonsense")),
1542            Err(BuildError::Format(_))
1543        ));
1544        // `raw` is not inferable -- a `.bin` of pixel bytes is a file nothing
1545        // reads back -- so it is named rather than guessed.
1546        assert!(matches!(
1547            canvas.to_file(directory.join("out.bin")),
1548            Err(BuildError::Format(_))
1549        ));
1550        canvas
1551            .to_file_as(directory.join("out.bin"), Format::Raw)
1552            .unwrap_or_else(|error| unreachable!("{error}"));
1553    }
1554
1555    #[test]
1556    fn a_data_url_carries_the_format_and_the_bytes() {
1557        let renderer = Renderer::new();
1558        let mut canvas = Root::new(4.0)
1559            .height(4.0)
1560            .render(&renderer)
1561            .unwrap_or_else(|error| unreachable!("{error}"));
1562
1563        let url = canvas
1564            .to_url(Format::Png)
1565            .unwrap_or_else(|error| unreachable!("{error}"));
1566
1567        assert!(url.starts_with("data:image/png;base64,"), "{url}");
1568        // The PNG signature, base64-encoded, is what every PNG data URL opens
1569        // with -- so this says the bytes are the image rather than anything.
1570        assert!(url.contains("iVBORw0KGgo"), "{url}");
1571    }
1572
1573    #[test]
1574    fn a_page_root_holds_the_tree_rather_than_wrapping_it() {
1575        let scene =
1576            scene_of(Root::new(10.0).height(10.0).children(
1577                Row::new().children([Text::new("a"), Text::new("b")]),
1578            ));
1579        let root = scene
1580            .get(scene.pages[0])
1581            .unwrap_or_else(|| unreachable!("no root"));
1582        let row = scene
1583            .get(root.children[0])
1584            .unwrap_or_else(|| unreachable!("no row"));
1585
1586        assert!(matches!(root.kind, NodeKind::Box));
1587        assert_eq!(row.children.len(), 2);
1588    }
1589}