blueprinter 0.1.0

Hand-drawn style diagram renderer CLI — turn SVG into sketchy SVG
Documentation
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
use clap::{Args, Parser, Subcommand};
use std::fs;
use std::path::Path;

use blueprinter::jitter::JitterConfig;
use blueprinter::render::{extract_mermaid_blocks, mermaid_to_svg, RenderError};
use blueprinter::svg::{export_to_png, export_to_webp, transform_svg, Theme, TransformOptions};

#[derive(Parser)]
#[command(name = "blueprinter")]
#[command(version)]
#[command(about = "Hand-drawn style diagram renderer CLI")]
#[command(
    long_about = "Turn SVG into sketchy SVG. Mermaid via mmdc and draw.io direct input are planned."
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

/// Styling options shared by `render` and `transform`.
#[derive(Args)]
struct StyleArgs {
    /// Theme name (blueprint, sumi, watercolor, chalk, marker, manga, none)
    #[arg(short, long, default_value = "blueprint")]
    theme: String,

    /// Seed for reproducible output
    #[arg(long)]
    seed: Option<u64>,

    /// Override SVG text font-family while preserving layout
    #[arg(long)]
    font_family: Option<String>,

    /// Maximum coordinate offset applied to jittered geometry
    #[arg(long)]
    jitter_amplitude: Option<f64>,

    /// Segment density used to subdivide jittered strokes
    #[arg(long)]
    jitter_frequency: Option<f64>,

    /// Relative stroke-width variation applied per shape
    #[arg(long)]
    jitter_stroke_width_var: Option<f64>,

    /// Extra font directory loaded into the rasterizer's fontdb (for raster
    /// output). Useful for cross-platform reproducibility — drop the desired
    /// TTF/OTF files in one folder and pass it here.
    #[arg(long)]
    font_dir: Option<String>,
}

/// Output options shared by `render` and `transform`.
#[derive(Args)]
struct OutputArgs {
    /// Output file path
    #[arg(short, long)]
    output: String,

    /// Output format (svg, png, webp). Inferred from output extension if omitted.
    #[arg(long)]
    format: Option<String>,

    /// Scale factor for raster output (default: 1.0)
    #[arg(long, default_value = "1.0")]
    scale: f32,

    /// Explicit output width (in pixels, for raster formats)
    #[arg(long)]
    width: Option<u32>,

    /// Explicit output height (in pixels, for raster formats)
    #[arg(long)]
    height: Option<u32>,
}

#[derive(Subcommand)]
enum Commands {
    /// Render a Mermaid diagram (via external `mmdc`) into hand-drawn output
    Render {
        /// Input Mermaid file path (.mmd / .mermaid)
        #[arg(short, long)]
        input: String,

        #[command(flatten)]
        style: StyleArgs,

        #[command(flatten)]
        output_args: OutputArgs,
    },
    /// Transform an existing SVG's appearance without changing layout
    Transform {
        /// Input SVG file path
        #[arg(short, long)]
        input: String,

        #[command(flatten)]
        style: StyleArgs,

        #[command(flatten)]
        output_args: OutputArgs,
    },
    /// Convert input to another format (planned; not implemented yet)
    Convert {
        /// Input file path
        #[arg(short, long)]
        input: String,

        /// Output file path
        #[arg(short, long)]
        output: String,
    },
    /// Batch-render every ` ```mermaid ` block in a Markdown file
    Md {
        /// Input Markdown file path
        #[arg(short, long)]
        input: String,

        /// Output directory (created if it does not exist). Files are named
        /// `<md-stem>-<index>.<ext>` where index starts at 1.
        #[arg(short, long)]
        out_dir: String,

        #[command(flatten)]
        style: StyleArgs,

        /// Output format (svg, png, webp). Default: svg.
        #[arg(long, default_value = "svg")]
        format: String,

        /// Scale factor for raster output (default: 1.0)
        #[arg(long, default_value = "1.0")]
        scale: f32,

        /// Explicit output width (in pixels, for raster formats)
        #[arg(long)]
        width: Option<u32>,

        /// Explicit output height (in pixels, for raster formats)
        #[arg(long)]
        height: Option<u32>,
    },
}

fn main() {
    let cli = Cli::parse();

    match cli.command {
        Commands::Render {
            input,
            style,
            output_args,
        } => {
            let mermaid = read_input(&input);
            let svg = match mermaid_to_svg(&mermaid) {
                Ok(svg) => svg,
                Err(RenderError::MmdcNotFound) => {
                    eprintln!("Error: {}", RenderError::MmdcNotFound);
                    std::process::exit(127);
                }
                Err(err) => {
                    eprintln!("Error: {err}");
                    std::process::exit(1);
                }
            };
            run_pipeline(&svg, &input, &style, &output_args, "rendered");
        }
        Commands::Transform {
            input,
            style,
            output_args,
        } => {
            let svg = read_input(&input);
            run_pipeline(&svg, &input, &style, &output_args, "transformed");
        }
        Commands::Convert { input, output } => {
            eprintln!("Error: convert is not implemented yet.");
            let _ = (input, output);
            std::process::exit(1);
        }
        Commands::Md {
            input,
            out_dir,
            style,
            format,
            scale,
            width,
            height,
        } => {
            run_md_batch(&input, &out_dir, &style, &format, scale, width, height);
        }
    }
}

fn run_md_batch(
    input_path: &str,
    out_dir: &str,
    style: &StyleArgs,
    format: &str,
    scale: f32,
    width: Option<u32>,
    height: Option<u32>,
) {
    let md = read_input(input_path);
    let blocks = extract_mermaid_blocks(&md);
    if blocks.is_empty() {
        eprintln!("No `mermaid` code blocks found in {input_path}.");
        std::process::exit(0);
    }

    if let Err(err) = fs::create_dir_all(out_dir) {
        eprintln!("Error: failed to create output directory '{out_dir}': {err}");
        std::process::exit(1);
    }

    let stem = Path::new(input_path)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("diagram");
    let ext = match format {
        "svg" | "png" | "webp" => format,
        _ => {
            eprintln!("Error: unknown format '{format}'. Supported: svg, png, webp.");
            std::process::exit(1);
        }
    };

    let mut failures = 0usize;
    for (index, mermaid) in blocks.iter().enumerate() {
        let n = index + 1;
        let out_path = Path::new(out_dir).join(format!("{stem}-{n}.{ext}"));
        let out_str = out_path.to_string_lossy().into_owned();

        let svg = match mermaid_to_svg(mermaid) {
            Ok(svg) => svg,
            Err(RenderError::MmdcNotFound) => {
                eprintln!("Error: {}", RenderError::MmdcNotFound);
                std::process::exit(127);
            }
            Err(err) => {
                eprintln!("[{n}/{total}] mmdc failed: {err}", total = blocks.len());
                failures += 1;
                continue;
            }
        };

        let output_args = OutputArgs {
            output: out_str.clone(),
            format: Some(ext.to_string()),
            scale,
            width,
            height,
        };
        let label = format!("{input_path}#{n}");
        run_pipeline(&svg, &label, style, &output_args, "rendered");
    }

    if failures > 0 {
        eprintln!(
            "{failures}/{total} blocks failed (other blocks were written successfully).",
            total = blocks.len(),
        );
        std::process::exit(1);
    }
}

fn read_input(path: &str) -> String {
    match fs::read_to_string(path) {
        Ok(content) => content,
        Err(err) => {
            eprintln!("Error: failed to read input '{path}': {err}");
            std::process::exit(1);
        }
    }
}

fn run_pipeline(svg: &str, input_label: &str, style: &StyleArgs, out: &OutputArgs, verb: &str) {
    let theme_enum = match parse_theme(&style.theme) {
        Some(t) => t,
        None => {
            eprintln!(
                "Error: theme `{}` is not supported. Valid: blueprint, sumi, watercolor, chalk, marker, manga, none.",
                style.theme
            );
            std::process::exit(1);
        }
    };
    let config = jitter_config_from_flags(
        style.jitter_amplitude,
        style.jitter_frequency,
        style.jitter_stroke_width_var,
    );
    let options = TransformOptions {
        seed: style.seed,
        font_family_override: style.font_family.clone(),
        theme: theme_enum,
    };
    let transformed = match transform_svg(svg, &config, &options) {
        Ok(svg) => svg,
        Err(err) => {
            eprintln!("Error: failed to transform SVG: {err}");
            std::process::exit(1);
        }
    };

    let output_format = out
        .format
        .as_deref()
        .unwrap_or_else(|| infer_format_from_path(&out.output));

    let font_dir = style.font_dir.as_deref().map(Path::new);
    let result = match output_format {
        "svg" => fs::write(&out.output, &transformed).map_err(|e| e.to_string()),
        "png" => export_to_png(
            &transformed,
            build_dimensions(out.width, out.height),
            out.scale,
            font_dir,
        )
        .and_then(|bytes| fs::write(&out.output, bytes).map_err(|e| e.to_string())),
        "webp" => export_to_webp(
            &transformed,
            build_dimensions(out.width, out.height),
            out.scale,
            font_dir,
        )
        .and_then(|bytes| fs::write(&out.output, bytes).map_err(|e| e.to_string())),
        _ => {
            eprintln!("Error: unknown format '{output_format}'. Supported: svg, png, webp.");
            std::process::exit(1);
        }
    };

    if let Err(err) = result {
        eprintln!("Error: failed to write output {output_format}: {err}");
        std::process::exit(1);
    }

    println!(
        "{verb}: {input_label} -> {output} (theme: {theme}, format: {output_format})",
        output = out.output,
        theme = style.theme,
    );
}

fn parse_theme(name: &str) -> Option<Theme> {
    match name {
        "blueprint" => Some(Theme::Blueprint),
        "sumi" => Some(Theme::Sumi),
        "watercolor" => Some(Theme::Watercolor),
        "chalk" => Some(Theme::Chalk),
        "marker" => Some(Theme::Marker),
        "manga" => Some(Theme::Manga),
        "none" => Some(Theme::None),
        _ => None,
    }
}

fn jitter_config_from_flags(
    amplitude: Option<f64>,
    frequency: Option<f64>,
    stroke_width_var: Option<f64>,
) -> JitterConfig {
    let mut config = JitterConfig::default();
    if let Some(value) = amplitude {
        config.amplitude = value;
    }
    if let Some(value) = frequency {
        config.frequency = value;
    }
    if let Some(value) = stroke_width_var {
        config.stroke_width_var = value;
    }
    config
}

fn infer_format_from_path(path: &str) -> &'static str {
    let path = Path::new(path);
    match path.extension().and_then(|ext| ext.to_str()) {
        Some("png") => "png",
        Some("webp") => "webp",
        Some("svg") => "svg",
        _ => "svg",
    }
}

fn build_dimensions(width: Option<u32>, height: Option<u32>) -> Option<(Option<u32>, Option<u32>)> {
    match (width, height) {
        (None, None) => None,
        (Some(w), Some(h)) => Some((Some(w), Some(h))),
        (Some(w), None) => Some((Some(w), None)),
        (None, Some(h)) => Some((None, Some(h))),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn assert_transform_command(cli: Cli) -> (StyleArgs, OutputArgs) {
        match cli.command {
            Commands::Transform {
                style, output_args, ..
            } => (style, output_args),
            _ => panic!("expected transform command"),
        }
    }

    #[test]
    fn transform_cli_defaults_match_jitter_defaults() {
        let cli =
            Cli::try_parse_from(["blueprinter", "transform", "-i", "in.svg", "-o", "out.svg"])
                .unwrap();
        let (style, out) = assert_transform_command(cli);

        assert_eq!(style.font_family, None);
        assert_eq!(out.scale, 1.0);
        assert_eq!(out.width, None);
        assert_eq!(out.height, None);
        assert_eq!(out.format, None);

        assert_eq!(
            jitter_config_from_flags(
                style.jitter_amplitude,
                style.jitter_frequency,
                style.jitter_stroke_width_var
            ),
            JitterConfig::default()
        );
    }

    #[test]
    fn transform_cli_accepts_explicit_jitter_flags() {
        let cli = Cli::try_parse_from([
            "blueprinter",
            "transform",
            "-i",
            "in.svg",
            "-o",
            "out.svg",
            "--jitter-amplitude",
            "3.5",
            "--jitter-frequency",
            "7",
            "--jitter-stroke-width-var",
            "0.4",
            "--font-family",
            "Virgil",
        ])
        .unwrap();
        let (style, _) = assert_transform_command(cli);

        assert_eq!(style.font_family.as_deref(), Some("Virgil"));
        assert_eq!(
            jitter_config_from_flags(
                style.jitter_amplitude,
                style.jitter_frequency,
                style.jitter_stroke_width_var
            ),
            JitterConfig {
                amplitude: 3.5,
                frequency: 7.0,
                stroke_width_var: 0.4,
            }
        );
    }

    #[test]
    fn render_cli_accepts_same_style_flags_as_transform() {
        let cli = Cli::try_parse_from([
            "blueprinter",
            "render",
            "-i",
            "diagram.mmd",
            "-o",
            "out.png",
            "--theme",
            "manga",
            "--seed",
            "7",
            "--width",
            "800",
        ])
        .unwrap();

        let Commands::Render {
            input,
            style,
            output_args,
        } = cli.command
        else {
            panic!("expected render command");
        };

        assert_eq!(input, "diagram.mmd");
        assert_eq!(style.theme, "manga");
        assert_eq!(style.seed, Some(7));
        assert_eq!(output_args.width, Some(800));
    }

    #[test]
    fn parse_theme_known_values() {
        assert_eq!(parse_theme("manga"), Some(Theme::Manga));
        assert_eq!(parse_theme("chalk"), Some(Theme::Chalk));
        assert_eq!(parse_theme("none"), Some(Theme::None));
        assert_eq!(parse_theme("nonsense"), None);
    }

    #[test]
    fn infer_format_from_path_svg() {
        assert_eq!(infer_format_from_path("output.svg"), "svg");
    }

    #[test]
    fn infer_format_from_path_png() {
        assert_eq!(infer_format_from_path("output.png"), "png");
    }

    #[test]
    fn infer_format_from_path_webp() {
        assert_eq!(infer_format_from_path("output.webp"), "webp");
    }

    #[test]
    fn infer_format_from_path_default() {
        assert_eq!(infer_format_from_path("output.txt"), "svg");
    }

    #[test]
    fn build_dimensions_both() {
        assert_eq!(
            build_dimensions(Some(100), Some(200)),
            Some((Some(100), Some(200)))
        );
    }

    #[test]
    fn build_dimensions_width_only() {
        assert_eq!(build_dimensions(Some(100), None), Some((Some(100), None)));
    }

    #[test]
    fn build_dimensions_height_only() {
        assert_eq!(build_dimensions(None, Some(200)), Some((None, Some(200))));
    }

    #[test]
    fn build_dimensions_none() {
        assert_eq!(build_dimensions(None, None), None);
    }
}