meo-canvas-cli 0.1.0

Command-line renderer for meo-canvas scene files.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! Renders a scene file to an image from the command line.
//!
//! The surface that exists to make the pipeline usable without writing a
//! program: read an encoded scene, render it, write the bytes. It is also the
//! only place in the workspace that touches the network, and only when built
//! with `--features net`.
//!
//! # What this crate deliberately excludes
//!
//! No scene authoring. The CLI reads the binary format
//! [`meo_canvas_scene::codec`] defines; it does not parse a text or JSON
//! description into one. A second authoring syntax is a second thing that can
//! disagree with the scene types, and the Node addon and the Rust API already
//! cover authoring.
//!
//! No async runtime, with or without `net`. Fetching goes through a blocking
//! client, because a command-line renderer runs one job and exits -- there is
//! nothing for an executor to overlap it with.
//!
//! # Exit codes
//!
//! Distinct per failure class, so a script can branch on what went wrong
//! without parsing the message. `2` belongs to clap and is what a misspelled
//! flag produces.
//!
//! | code | meaning |
//! | ---- | ------- |
//! | 0 | the image was written |
//! | 2 | the command line was not understood |
//! | 3 | an input or output file could not be read or written |
//! | 4 | the scene file is not a scene this revision reads |
//! | 5 | a font could not be registered |
//! | 6 | the scene names a source this build cannot obtain |
//! | 7 | a render pass failed |

// **Nothing in this workspace writes `unsafe`, and this is what keeps it that
// way.** Measured before it was declared: zero occurrences of the token across
// every `crates/*/src`. A renderer reaching a C++ library through two binding
// layers is exactly the crate where an `unsafe` would look reasonable and go
// unquestioned, and the declaration turns adding one into a decision someone
// has to make deliberately rather than a line that passes review.
//
// The integration tests are separate crates and are not covered: the
// allocator that measures `codec::decode`'s reservation has to be an
// `unsafe impl GlobalAlloc`. That is the only `unsafe` in the repository and
// it exists to measure a defect.
#![forbid(unsafe_code)]
// The CLI's whole output contract is stdout and stderr: the rendered bytes go
// to a file or to stdout, and progress goes to stderr. `print_stdout` is a
// warning aimed at libraries that log where a caller cannot intercept it, which
// does not describe a program whose stdout is the deliverable.
#![allow(
    clippy::print_stdout,
    reason = "stdout is this binary's output channel"
)]

use std::{
    io::Write as _,
    path::{Path, PathBuf},
    process::ExitCode,
};

use clap::{Parser, Subcommand};
use meo_canvas_core::{
    Error, ImageFormat, Renderer, chained, encode::EncodeOptions,
};
use meo_canvas_scene::Scene;

/// An input or output file could not be read or written.
const EXIT_IO: u8 = 3;
/// The bytes are not a scene this revision reads.
const EXIT_MALFORMED_SCENE: u8 = 4;
/// A font file could not be registered.
const EXIT_FONT: u8 = 5;
/// The scene names an image this build cannot obtain by itself.
const EXIT_UNRESOLVED_SOURCE: u8 = 6;
/// Resolve, measure, layout, paint or encode failed.
const EXIT_RENDER: u8 = 7;

/// Renders a `meo-canvas` scene file to an image.
#[derive(Debug, Parser)]
#[command(name = "meo-canvas", version, about)]
struct Cli {
    /// What to do.
    #[command(subcommand)]
    command: Command,
}

/// The verbs the binary offers.
///
/// A subcommand rather than a bare set of flags, so that a second verb -- an
/// inspector, a fixture recorder -- is an addition rather than a break in the
/// command line that already shipped.
#[derive(Debug, Subcommand)]
enum Command {
    /// Renders a scene file to an image.
    Render(RenderArgs),
}

/// Everything `render` takes.
#[derive(Debug, Parser)]
struct RenderArgs {
    /// Encoded scene file to render.
    scene: PathBuf,

    /// Where to write the image. Writes to stdout when absent.
    #[arg(short, long)]
    output: Option<PathBuf>,

    /// Container to encode in. Taken from the output file's extension when
    /// absent.
    #[arg(short, long)]
    format: Option<String>,

    /// A font face, as `family=path`. Repeat it to give one family several
    /// weights, or to register several families.
    #[arg(long = "font", value_name = "FAMILY=PATH")]
    fonts: Vec<String>,

    /// Lossy quality from 0.0 to 1.0, read by JPEG, WebP and AVIF.
    #[arg(long)]
    quality: Option<f32>,

    /// Encode WebP without loss.
    #[arg(long)]
    lossless: bool,

    /// Which page a single-page format writes, counting from zero.
    #[arg(long)]
    page: Option<usize>,

    /// Frames per second for an animated format.
    #[arg(long)]
    fps: Option<f32>,

    /// How many times an animation plays. Absent plays it forever.
    #[arg(long)]
    loops: Option<u32>,
}

/// A failure with the exit code that names its class.
#[derive(Debug)]
struct Failure {
    /// What to print on stderr.
    message: String,
    /// What to exit with.
    code: u8,
}

impl Failure {
    /// Builds a failure from anything printable.
    fn new(message: impl Into<String>, code: u8) -> Self {
        Self {
            message: message.into(),
            code,
        }
    }
}

/// The exit code a core failure belongs to.
///
/// Mapped per variant rather than collapsed to one code, because the three a
/// caller can act on differ: a missing font is fixed by passing `--font`, an
/// unresolved source by building with `net`, and a malformed scene by
/// re-encoding it.
const fn exit_code_for(error: &Error) -> u8 {
    match error {
        Error::UnresolvedSource(_) => EXIT_UNRESOLVED_SOURCE,
        Error::UnknownFont(_) | Error::FontRegister { .. } => EXIT_FONT,
        Error::ImageRead { .. } => EXIT_IO,
        _ => EXIT_RENDER,
    }
}

/// The message a failure prints, with the part the caller can act on.
///
/// A core error says what went wrong; only the CLI knows that a URL source is
/// obtainable by a different build of itself. Naming the feature turns "this
/// crate does not fetch" into an instruction.
fn explain(error: &Error) -> String {
    match error {
        Error::UnresolvedSource(_) if cfg!(not(feature = "net")) => {
            format!("{error}; build with `--features net` to fetch it")
        }
        // The chain, not just this variant's own sentence: `Error::Scene` and
        // `Error::ImageRead` carry their cause as `#[source]`, and a command
        // line that printed only the outer message told a caller a font or an
        // image failed without saying why.
        other => chained(other),
    }
}

/// Splits a `family=path` pair.
///
/// The family is named rather than read from the file because that is the name
/// a scene's `fontFamily` has to match, and a caller who wants their file
/// called something else should not have to rename the file. `canvas.type.ts`
/// settled the same shape as `{ family, paths[] }`.
fn parse_font(pair: &str) -> Result<(&str, &Path), Failure> {
    let (family, path) = pair.split_once('=').ok_or_else(|| {
        Failure::new(
            format!("--font expects `family=path`, not {pair:?}"),
            EXIT_FONT,
        )
    })?;

    if family.is_empty() {
        return Err(Failure::new(
            format!("--font {pair:?} names no family"),
            EXIT_FONT,
        ));
    }

    Ok((family, Path::new(path)))
}

/// Works out which container to write.
///
/// A named format wins; otherwise the output file's extension names one. There
/// is no default: writing a PNG because nothing said otherwise turns a
/// misspelled `--format` into a silently wrong file.
fn resolve_format(args: &RenderArgs) -> Result<ImageFormat, Failure> {
    if let Some(name) = &args.format {
        return ImageFormat::from_extension(name).ok_or_else(|| {
            Failure::new(format!("{name:?} names no format"), EXIT_IO)
        });
    }

    let extension = args
        .output
        .as_ref()
        .and_then(|path| path.extension())
        .and_then(std::ffi::OsStr::to_str)
        .ok_or_else(|| {
            Failure::new(
                "no --format, and the output names no extension to infer one from",
                EXIT_IO,
            )
        })?;

    ImageFormat::from_extension(extension).ok_or_else(|| {
        Failure::new(
            format!("the output extension {extension:?} names no format"),
            EXIT_IO,
        )
    })
}

/// Reads and decodes the scene file.
fn read_scene(path: &Path) -> Result<Scene, Failure> {
    let bytes = std::fs::read(path).map_err(|source| {
        Failure::new(
            format!("cannot read {}: {source}", path.display()),
            EXIT_IO,
        )
    })?;

    meo_canvas_scene::codec::decode(&bytes).map_err(|source| {
        Failure::new(
            format!(
                "{} is not a scene this build reads: {source}",
                path.display()
            ),
            EXIT_MALFORMED_SCENE,
        )
    })
}

/// Builds the renderer every `--font` pair is registered into.
///
/// The renderer owns the fonts, so registering them is building it: a caller
/// rendering a thousand scenes registers once and the faces outlive any one
/// scene.
fn build_renderer(pairs: &[String]) -> Result<Renderer, Failure> {
    let mut renderer = Renderer::new();
    for pair in pairs {
        let (family, path) = parse_font(pair)?;
        renderer
            .register_font(family, path)
            .map_err(|source| Failure::new(explain(&source), EXIT_FONT))?;
    }
    Ok(renderer)
}

/// Turns the flags into the encoder's options.
fn encode_options(args: &RenderArgs) -> EncodeOptions {
    EncodeOptions {
        quality: args.quality,
        // Only sent when asked for: a `false` here would override the
        // renderer's own default rather than leave it alone.
        lossless: args.lossless.then_some(true),
        matte: None,
        page: args.page,
        fps: args.fps,
        frame_delays: Vec::new(),
        loops: args.loops,
    }
}

/// Writes the encoded bytes where the caller asked for them.
fn write_output(bytes: &[u8], output: Option<&Path>) -> Result<(), Failure> {
    output.map_or_else(
        || {
            std::io::stdout().write_all(bytes).map_err(|source| {
                Failure::new(
                    format!("cannot write to stdout: {source}"),
                    EXIT_IO,
                )
            })
        },
        |path| {
            std::fs::write(path, bytes).map_err(|source| {
                Failure::new(
                    format!("cannot write {}: {source}", path.display()),
                    EXIT_IO,
                )
            })
        },
    )
}

/// Reads the scene, renders it, and writes the result.
fn render(args: &RenderArgs) -> Result<(), Failure> {
    let format = resolve_format(args)?;
    let scene = read_scene(&args.scene)?;
    let renderer = build_renderer(&args.fonts)?;
    let options = encode_options(args);

    let image = renderer
        .render_to_buffer(&scene, format, &options)
        .map_err(|error| {
            Failure::new(explain(&error), exit_code_for(&error))
        })?;

    write_output(&image, args.output.as_deref())
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    let Command::Render(args) = &cli.command;

    match render(args) {
        Ok(()) => ExitCode::SUCCESS,
        Err(failure) => {
            eprintln!("meo-canvas: {}", failure.message);
            ExitCode::from(failure.code)
        }
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use meo_canvas_core::Error;

    use super::{
        EXIT_FONT, EXIT_IO, EXIT_UNRESOLVED_SOURCE, ImageFormat, RenderArgs,
        encode_options, exit_code_for, parse_font, resolve_format,
    };

    /// The arguments a caller who named nothing optional would produce.
    fn bare(scene: &str, output: Option<&str>) -> RenderArgs {
        RenderArgs {
            scene: PathBuf::from(scene),
            output: output.map(PathBuf::from),
            format: None,
            fonts: Vec::new(),
            quality: None,
            lossless: false,
            page: None,
            fps: None,
            loops: None,
        }
    }

    #[test]
    fn a_font_pair_splits_on_the_first_equals() {
        // A path may contain `=`, so only the first one separates. Splitting on
        // the last would take a family called `Inter` and a file called
        // `a=b.ttf` and produce a family called `Inter=a`.
        let (family, path) = parse_font("Inter=/fonts/a=b.ttf")
            .unwrap_or_else(|failure| unreachable!("{}", failure.message));

        assert_eq!(family, "Inter");
        assert_eq!(path.to_string_lossy(), "/fonts/a=b.ttf");
    }

    #[test]
    fn a_font_without_a_family_is_refused() {
        for pair in ["/fonts/Inter.ttf", "=/fonts/Inter.ttf"] {
            let failure = parse_font(pair)
                .err()
                .unwrap_or_else(|| unreachable!("{pair} names no family"));
            assert_eq!(failure.code, EXIT_FONT);
        }
    }

    #[test]
    fn the_output_extension_names_the_format() {
        let args = bare("scene.mcs", Some("out.webp"));
        let format = resolve_format(&args)
            .unwrap_or_else(|failure| unreachable!("{}", failure.message));

        assert_eq!(format, ImageFormat::Webp);
    }

    #[test]
    fn a_named_format_wins_over_the_extension() {
        let mut args = bare("scene.mcs", Some("out.webp"));
        args.format = Some("png".to_owned());

        let format = resolve_format(&args)
            .unwrap_or_else(|failure| unreachable!("{}", failure.message));

        assert_eq!(format, ImageFormat::Png);
    }

    #[test]
    fn a_name_and_an_extension_that_name_no_format_are_both_refused() {
        // Two paths to the same refusal, and both carry the offending spelling
        // so the caller sees what they typed rather than only that it failed.
        let mut named = bare("scene.mcs", Some("out.png"));
        named.format = Some("nonsense".to_owned());
        let failure = resolve_format(&named)
            .err()
            .unwrap_or_else(|| unreachable!("nonsense names no format"));
        assert_eq!(failure.code, EXIT_IO);
        assert!(failure.message.contains("nonsense"), "{}", failure.message);

        let inferred = bare("scene.mcs", Some("out.xyz"));
        let failure = resolve_format(&inferred)
            .err()
            .unwrap_or_else(|| unreachable!("xyz names no format"));
        assert_eq!(failure.code, EXIT_IO);
        assert!(failure.message.contains("xyz"), "{}", failure.message);
    }

    #[test]
    fn an_unreadable_image_is_an_io_class_rather_than_a_render_one() {
        // The caller's fix is a filesystem one -- the path in the scene is
        // wrong or unreadable -- so it reads as I/O rather than sending them to
        // look at the renderer.
        let error = Error::image_read(
            "/no-such-directory/a.png".to_owned(),
            std::io::Error::from(std::io::ErrorKind::NotFound),
        );

        assert_eq!(exit_code_for(&error), EXIT_IO);
    }

    #[test]
    fn nothing_to_infer_from_is_refused_rather_than_defaulted() {
        // Defaulting to PNG would turn a misspelled `--format` into a silently
        // wrong file rather than a message.
        for output in [None, Some("out")] {
            let failure = resolve_format(&bare("scene.mcs", output))
                .err()
                .unwrap_or_else(|| unreachable!("nothing names a format"));
            assert_eq!(failure.code, EXIT_IO);
        }
    }

    #[test]
    fn an_unset_flag_leaves_the_renderers_default() {
        // `--lossless` absent sends `None`, not `Some(false)`: the second would
        // override a default this crate has no opinion about.
        let options = encode_options(&bare("scene.mcs", Some("out.webp")));

        assert_eq!(options.lossless, None);
        assert_eq!(options.fps, None);
        assert_eq!(options.quality, None);
    }

    /// A temporary path this process alone writes to.
    ///
    /// The process id is in it because these tests write a fixed name into a
    /// shared temporary directory, and cargo runs a crate's test binaries
    /// concurrently -- the unit tests here and the integration tests beside
    /// them are separate processes. Two of them sharing a path is a write, a
    /// delete and a read racing, which fails as a missing file in whichever
    /// one read last.
    fn scratch(name: &str) -> PathBuf {
        std::env::temp_dir()
            .join(format!("meo-canvas-cli-{}-{name}", std::process::id()))
    }

    #[test]
    fn a_named_output_receives_the_bytes_and_an_unwritable_path_is_an_io_failure()
     {
        let path = scratch("write-output.bin");

        super::write_output(b"pixels", Some(&path))
            .unwrap_or_else(|failure| unreachable!("{}", failure.message));
        let written = std::fs::read(&path)
            .unwrap_or_else(|source| unreachable!("{source}"));
        assert_eq!(written, b"pixels");
        drop(std::fs::remove_file(&path));

        // A directory that does not exist is the ordinary way this fails, and
        // it is an I/O class rather than a render one.
        let missing = path.join("no-such-directory").join("out.png");
        let failure = super::write_output(b"pixels", Some(&missing))
            .err()
            .unwrap_or_else(|| {
                unreachable!("a missing directory cannot be written to")
            });
        assert_eq!(failure.code, EXIT_IO);
    }

    #[test]
    fn bytes_that_are_not_a_scene_are_a_distinct_failure_from_a_missing_file() {
        let path = scratch("not-a-scene.mcs");
        std::fs::write(&path, b"not a scene at all")
            .unwrap_or_else(|source| unreachable!("{source}"));

        let malformed = super::read_scene(&path)
            .err()
            .unwrap_or_else(|| unreachable!("those bytes are not a scene"));
        drop(std::fs::remove_file(&path));

        let missing = super::read_scene(std::path::Path::new(
            "/no-such-directory/no-such-scene.mcs",
        ))
        .err()
        .unwrap_or_else(|| unreachable!("that file does not exist"));

        assert_eq!(malformed.code, super::EXIT_MALFORMED_SCENE);
        assert_eq!(missing.code, EXIT_IO);
        assert_ne!(malformed.code, missing.code);
    }

    #[test]
    fn a_font_file_that_is_not_there_fails_as_a_font_rather_than_as_io() {
        // The caller's fix is the same either way -- pass a `--font` that
        // exists -- so it reads as a font failure rather than sending them to
        // look at the scene file.
        let failure = super::build_renderer(&[
            "Inter=/no-such-directory/Inter.ttf".to_owned(),
        ])
        .err()
        .unwrap_or_else(|| unreachable!("that font is not there"));

        assert_eq!(failure.code, EXIT_FONT);
    }

    #[test]
    fn registering_nothing_succeeds_and_leaves_the_platforms_faces() {
        assert!(super::build_renderer(&[]).is_ok());
    }

    #[test]
    fn a_url_source_names_the_feature_that_would_fetch_it() {
        let message = super::explain(&Error::UnresolvedSource(
            meo_canvas_scene::NodeId::ROOT,
        ));

        if cfg!(feature = "net") {
            assert!(!message.contains("--features net"));
        } else {
            assert!(
                message.contains("--features net"),
                "the message should say how to obtain it: {message}"
            );
        }
    }

    #[test]
    fn each_failure_class_exits_differently() {
        // A script branches on these, so two classes sharing a code would make
        // "add a font" and "build with net" indistinguishable.
        let unresolved = exit_code_for(&Error::UnresolvedSource(
            meo_canvas_scene::NodeId::ROOT,
        ));
        let font = exit_code_for(&Error::UnknownFont("Inter".to_owned()));
        let layout = exit_code_for(&Error::Layout("no".to_owned()));

        assert_eq!(unresolved, EXIT_UNRESOLVED_SOURCE);
        assert_eq!(font, EXIT_FONT);
        assert_ne!(layout, unresolved);
        assert_ne!(layout, font);
    }
}