diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b68b2b393..693d14baa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,6 +34,7 @@ jobs: converters: - '.github/workflows/ci.yml' - 'converters/**' + - 'extensions/**' - 'acdc-parser/**' - 'Cargo.toml' - 'Cargo.lock' @@ -43,6 +44,7 @@ jobs: - 'acdc-execute/**' - 'acdc-parser/**' - 'converters/**' + - 'extensions/**' - 'Cargo.toml' - 'Cargo.lock' lsp: @@ -156,8 +158,8 @@ jobs: run: | sudo apt-get update sudo apt-get install -y groff mandoc - - name: Run converter tests - run: cargo nextest run -p acdc-converters-core -p acdc-converters-html -p acdc-converters-manpage -p acdc-converters-terminal -p acdc-converters-markdown --all-features --verbose + - name: Run converter and native extension tests + run: cargo nextest run -p acdc-converters-core -p acdc-converters-html -p acdc-converters-manpage -p acdc-converters-terminal -p acdc-converters-markdown -p acdc-diagram --all-features --verbose - name: Run HTML tests - no default features run: cargo nextest run -p acdc-converters-html --no-default-features --verbose - name: Run HTML tests - highlighting @@ -201,6 +203,10 @@ jobs: run: cargo nextest run -p acdc-cli -p acdc-execute --all-features --verbose --no-tests warn --test-threads 1 # we've added this until https://github.com/nextest-rs/nextest/pull/3553 gets merged - name: Run execute-only tests run: cargo nextest run -p acdc-cli -p acdc-execute --no-default-features --features execute --verbose --test-threads 1 + - name: Test diagram availability and activation + run: | + cargo nextest run -p acdc-cli --no-default-features --features html --test cli -E 'test(diagram::)' + cargo nextest run -p acdc-cli --no-default-features --features html,diagram --test cli -E 'test(diagram::)' - name: Test execute with the parser network capability run: cargo nextest run -p acdc-execute --no-default-features --features acdc-parser/network -E 'test(substitution_is_independent_of_optional_capabilities)' --verbose - name: Smoke-test backend-only CLI builds diff --git a/AGENTS.md b/AGENTS.md index 4dcdf96fb..02cfea7c5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,6 +49,7 @@ crate; check the CLI manifest for backend and tool selection. | `asg` | off | parser, CLI | Checked upstream and named acdc ASG export; independent of compatibility mode | | `tck` | off | CLI | Fixed Draft-mode TCK adapter; enables `asg` | | `network` | off | parser, html, pdf | Remote includes and HTML/PDF image access; caller permission and safe mode still apply | +| `diagram` | off | CLI | Makes native diagram styles available via `--extension diagram` with caller-selected executables in unsafe mode | | `highlighting` | off | html, terminal | giallo source highlighting | | `terminal` | off | html | Renders terminal previews into HTML; the cli exposes it as `html-terminal` | | `emulator` | off | terminal | Runs terminal output through a libghostty-vt terminal emulator and captures the rendered screen grid (static previews + session replays); the cli exposes it as `terminal-emulator` | diff --git a/Cargo.lock b/Cargo.lock index f9e46c0a9..2a17a0db5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12,6 +12,7 @@ dependencies = [ "acdc-converters-markdown", "acdc-converters-pdf", "acdc-converters-terminal", + "acdc-diagram", "acdc-execute", "acdc-lint", "acdc-parser", @@ -153,6 +154,24 @@ dependencies = [ "viuer", ] +[[package]] +name = "acdc-diagram" +version = "0.1.0" +dependencies = [ + "acdc-converters-core", + "acdc-converters-html", + "acdc-parser", + "base64 0.23.1", + "image", + "lopdf", + "png", + "roxmltree 0.21.1", + "sha2", + "svgtypes", + "tempfile", + "url", +] + [[package]] name = "acdc-editor-wasm" version = "0.6.0" diff --git a/Cargo.toml b/Cargo.toml index 8a727d2c6..edc59c1cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ members = [ "converters/pdf", "converters/pdf/crates/*", "converters/terminal", + "extensions/diagram", ] default-members = [ "acdc-cli", @@ -31,6 +32,7 @@ default-members = [ "converters/pdf", "converters/pdf/crates/*", "converters/terminal", + "extensions/diagram", ] resolver = "2" @@ -47,6 +49,7 @@ acdc-converters-manpage = { path = "converters/manpage", default-features = fals acdc-converters-markdown = { path = "converters/markdown" } acdc-converters-pdf = { path = "converters/pdf", default-features = false } acdc-converters-terminal = { path = "converters/terminal", default-features = false } +acdc-diagram = { path = "extensions/diagram" } acdc-execute = { path = "acdc-execute", default-features = false } acdc-lint = { path = "acdc-lint", default-features = false } acdc-parser = { path = "acdc-parser", default-features = false } diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 5e2b968a6..2c3322b25 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,102 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Honor renderer option defaults, `literal` and `jpg` format aliases, and explicit image dimensions on diagram file macros. + +- Caption local images with `meme::photo.jpg[Top,Bottom]` and `--extension diagram --magick PATH`. PNG is the default. Use `format=gif` for GIF and `opts=noupcase` to preserve letter case. + +- Render `[vegalite]` blocks and `vegalite::chart.json[]` files with `--vl2vg PATH`. Supply the Vega SVG renderer with `--vg2svg PATH`. The compiler feeds its Vega specification to the selected SVG or PNG renderer. + +- Render `[vega]` blocks and `vega::chart.json[]` files with `--vg2svg PATH`. SVG uses `--vg2svg`. Supply `--vg2png PATH` for PNG and `--vl2vg PATH` for Vega-Lite specifications. + +- Render `[salt]` blocks and `salt::chart.salt[]` files with `--plantuml PATH`. Supply the PlantUML executable to render Salt wireframes as PNG, SVG, or text. + +- Render `[plantuml]` blocks and `plantuml::chart.puml[]` files with `--plantuml PATH`. Choose PNG, SVG, ASCII `atxt`, or Unicode `txt` and `utxt`. Local includes resolve from the diagram directory. Configure Graphviz with `--graphviz-dot` or use the built-in Smetana layout. + +- Render `[penrose]` blocks and `penrose::chart.substance[]` files with `--roger PATH`. Provide `domain_file` and `style_file` relative to the diagram source. Use `variation` to choose a layout. + +- Render `[erd]` blocks and `erd::chart.erd[]` files with `--erd PATH`. Configure Graphviz with `--graphviz-dot PATH`. The ERD renderer produces DOT and Graphviz writes the final PNG or SVG. + +- Render `[lilypond]` blocks and `lilypond::chart.ly[]` files with `--lilypond PATH`. The output is a cropped PNG or PDF score. Set `resolution` to select the raster resolution. + +- Render `[oxdraw]` blocks and `oxdraw::chart.mmd[]` files with `--oxdraw PATH`. SVG is the default. Use `background` and `scale` to change the output. + +- Render `[mermaid]` blocks and `mermaid::chart.mmd[]` files with `--mmdc PATH`. Choose PNG or SVG and set `theme`, `scale`, or a local `config` file. For SVGs with a nonzero viewBox origin, acdc uses the declared width and height. Asciidoctor Diagram 3.2.1 subtracts the origin from those dimensions. + +- Render `[bpmn]` blocks and `bpmn::chart.bpmn[]` files with `--bpmn-js PATH`. Choose PNG (default), SVG, PDF, or JPEG. Set `width` and `height` to select the canvas size. + +- Render `[umlet]` blocks and `umlet::chart.uxf[]` files with `--umlet PATH`. Choose SVG (default), PNG, PDF, or GIF using a UMLet command-line launcher. Supports the SVG 1.0 declaration emitted by the standalone UMLet distribution. + +- Render `[gnuplot]` blocks and `gnuplot::chart.gp[]` files with `--gnuplot PATH`. Choose PNG, SVG, GIF, or a literal text plot. Set `width` and `height` together to select a terminal size. + +- Render `[tape]` blocks and `tape::chart.tape[]` files with `--vhs PATH`. GIF is the default. Use `format=svg` for an SVG recording. Tape scripts run in unsafe mode. + +- Render `[ditaa]` blocks and `ditaa::chart.ditaa[]` files with `--ditaa PATH`. Choose PNG (default), SVG, or literal text. Set `round-corners=true`, `shadows=false`, or `scale` to change the drawing. + +- Render `[diagrams]` blocks and `diagrams::chart.py[]` files with `--diagrams-python PATH`. Render Python diagrams as PNG (default), SVG, or PDF with an interpreter that has the diagrams package installed. + +- Render `[syntrax]` blocks and `syntrax::chart.spec[]` files with `--syntrax PATH`. Choose PNG or SVG. Use `heading`, `scale`, `style-file`, and `transparent=true` to customize a railroad diagram. + +- Render `[svgbob]` blocks and `svgbob::chart.bob[]` files with `--svgbob PATH`. Choose SVG or literal text. The SVG renderer accepts `font-family`, `font-size`, `stroke-width`, and `scale`. + +- Render `[a2s]` blocks and `a2s::chart.txt[]` files with `--a2s PATH`. SVG is the default. Use `format=txt` for the original text, `scalex` and `scaley` for dimensions, or `noblur=true` for crisp edges. + +- Render `[pintora]` blocks and `pintora::chart.pintora[]` files with `--pintora PATH`. Choose PNG (default) or SVG. Set `theme`, `width`, `background-color`, or `pixel-ratio` to customize the result. + +- Render `[symbolator]` blocks and `symbolator::chart.vhd[]` files with `--symbolator PATH`. Choose PNG (default), PDF, or SVG. + +- Render `[shaape]` blocks and `shaape::chart.shaape[]` files with `--shaape PATH`. PNG is the default. Select SVG with `format=svg`. + +- Render `[d2]` blocks and `d2::chart.d2[]` files with `--d2 PATH`. SVG is the default. PNG and PDF require the corresponding D2 browser support. Set `theme`, `layout`, or `sketch` to change the drawing. + +- Render `[graphviz_py]` blocks and `graphviz_py::chart.dot[]` files with `--graphviz-py PATH`. Choose PNG (default), PDF, or SVG. Set `layout` and `argument` to pass a layout engine and a preprocessor argument. + +- Render `[dbml]` blocks and `dbml::chart.dbml[]` files with `--dbml-renderer PATH`. Output is SVG. + +- Render `[smcat]` blocks and `smcat::chart.smcat[]` files with `--smcat PATH`. Set `direction` or `engine` to choose the SVG layout. + +- Render `[nomnoml]` blocks and `nomnoml::chart.nomnoml[]` files with `--nomnoml PATH`. Output is SVG. + +- Render `[rackdiag]` blocks and `rackdiag::chart.diag[]` files with `--rackdiag PATH`. PNG is the default. PDF, SVG, and a custom font file via `fontpath` are also supported. + +- Render `[packetdiag]` blocks and `packetdiag::chart.diag[]` files with `--packetdiag PATH`. PNG is the default. PDF, SVG, and a custom font file via `fontpath` are also supported. + +- Render `[nwdiag]` blocks and `nwdiag::chart.diag[]` files with `--nwdiag PATH`. PNG is the default. PDF, SVG, and a custom font file via `fontpath` are also supported. + +- Render `[actdiag]` blocks and `actdiag::chart.diag[]` files with `--actdiag PATH`. PNG is the default. PDF, SVG, and a custom font file via `fontpath` are also supported. + +- Render `[seqdiag]` blocks and `seqdiag::chart.diag[]` files with `--seqdiag PATH`. PNG is the default. PDF, SVG, and a custom font file via `fontpath` are also supported. + +- Render `[blockdiag]` blocks and `blockdiag::chart.diag[]` files with `--blockdiag PATH`. PNG is the default. PDF, SVG, and a custom font file via `fontpath` are also supported. + +- Render packet and binary layouts as SVG from `[bytefield]` blocks or `bytefield::layout.edn[]` file macros with `--extension diagram --bytefield-svg PATH`. + +- Render GoAT ASCII diagrams from `[goat]` blocks and `goat::chart.txt[]` file macros as SVG with `--extension diagram --goat PATH`. Set `svg-color-dark-scheme` and `svg-color-light-scheme` to choose the colors. + +- Render Pikchr source from `[pikchr]` blocks and `pikchr::chart.pikchr[]` file macros as SVG with `--extension diagram --pikchr PATH`. Syntax errors report the renderer’s diagnostic and preserve the previous image. + +- Render PIC source from `[dpic]` blocks or `dpic::chart.pic[]` file macros as SVG with `--extension diagram --dpic PATH`. acdc accepts both bare source and pictures already enclosed in `.PS` and `.PE`. Asciidoctor Diagram 3.2.1 can append a duplicate closing delimiter to a complete picture. + +- Render message sequence charts from `[msc]` blocks or `msc::chart.msc[svg]` with `--extension diagram --mscgen PATH`. PNG is the default. Use `font=` or `msc-font` to select a PNG font. + +- Render a local DOT file with `graphviz::chart.dot[svg,alt="*Graph*"]`. File macros use the configured Graphviz executable and share the document’s include byte limit. + +- Render Graphviz listing and literal blocks with the registered `dot` executable (`--extension diagram --graphviz-dot PATH` in the CLI). PNG is the default. SVG, PDF, and the `layout` setting are supported. + +- Set `imagesoutdir` to stage WaveDrom and TikZ files in a local relative directory. Linked images use `imagesdir`, and embedded images read the staged files. acdc rejects absolute directories and parent traversal. + +- Builds with the optional `diagram` feature can convert WaveDrom and TikZ listing + and literal blocks with `convert --extension diagram`. Supply `--wavedrom-cli PATH` for + WaveDrom or `--lualatex PATH` for TikZ. Add `--pdf2svg PATH` for TikZ SVG. + Diagrams can appear in list continuations, sidebars, and AsciiDoc table cells. + Setting `imagesoutdir` inside a cell stages only that cell’s diagrams there. + Set `diagram-svg-type` to `static`, `inline`, or `interactive` to choose how HTML presents SVG diagrams. + In HTML, SVG and PNG diagrams use their intrinsic dimensions by default. Set `scale=0.5` to display them at half size, or set `width` and `height` independently. + Rendering requires unsafe mode and a caller-selected executable. Add + `subs=attributes` to a diagram block to expand document attributes in its source. + Failed diagrams show the error and source in the output. Use `--fail-on-warnings` to + return status 1 after conversion, or `-a diagram-on-error=abort` to stop at the block. + - Statically linked converter registrations now supply the available backend names, aliases, and variants for CLI help and conversion. - Selected native text postprocessors run per input, including when multiple terminal documents share a pager. diff --git a/acdc-cli/Cargo.toml b/acdc-cli/Cargo.toml index d38c834b3..1a8c61c17 100644 --- a/acdc-cli/Cargo.toml +++ b/acdc-cli/Cargo.toml @@ -17,6 +17,7 @@ doc = false [dependencies] acdc-converters-core.workspace = true +acdc-diagram = { workspace = true, optional = true } acdc-execute = { workspace = true, optional = true } acdc-converters-html = { workspace = true, optional = true } acdc-lint = { workspace = true, optional = true } @@ -54,6 +55,7 @@ terminal = ["dep:acdc-converters-terminal"] # Terminal converter with ANSI co # Document tools lint = ["dep:acdc-lint"] # AsciiDoc lint command +diagram = ["dep:acdc-diagram"] # Native diagram styles; activate with --extension diagram # Syntax highlighting for source blocks in selected HTML and terminal backends. highlighting = [ diff --git a/acdc-cli/README.adoc b/acdc-cli/README.adoc index d558dc300..89e399ace 100644 --- a/acdc-cli/README.adoc +++ b/acdc-cli/README.adoc @@ -128,6 +128,36 @@ application. Repeat the option to select multiple packages in execution order; duplicate selections count once. Compiling or registering a package does not activate it. Unknown or unavailable names fail before input is read or parsed. +Build with `cargo build -p acdc-cli --features diagram` to make the `diagram` package available. +Select it for trusted documents and pass the paths to the tools you want to run. +Use `graphviz::graphs/chart.dot[svg]` to render an external DOT file as `chart.svg`. Graphviz accepts PNG (default), SVG, or PDF. PIC source in `[dpic]` blocks and `dpic::chart.pic[]` macros renders as SVG. Use `[pikchr]` or `pikchr::chart.pikchr[]` for Pikchr SVGs. Message sequence charts accept PNG (default) or SVG from `[msc]` blocks and `msc::chart.msc[]` macros. WaveDrom accepts SVG (default) or PNG. TikZ uses LuaLaTeX for PDF and can use pdf2svg for SVG. + +[source,console] +.... +acdc convert --extension diagram --graphviz-dot /usr/bin/dot manual.adoc +acdc convert --extension diagram --mscgen /usr/bin/mscgen manual.adoc +acdc convert --extension diagram --dpic /usr/bin/dpic manual.adoc +acdc convert --extension diagram --pikchr /usr/bin/pikchr manual.adoc +acdc convert --extension diagram --goat /usr/bin/goat manual.adoc +acdc convert --extension diagram --blockdiag /usr/bin/blockdiag manual.adoc +acdc convert --extension diagram --bytefield-svg /usr/bin/bytefield-svg manual.adoc +acdc convert --extension diagram --wavedrom-cli /opt/bin/wavedrom-cli manual.adoc +acdc convert --extension diagram --lualatex /opt/tex/bin/lualatex --pdf2svg /opt/bin/pdf2svg manual.adoc +.... + +The tool paths can be supplied together. Diagram blocks run only in unsafe mode (the CLI default). +Restricted modes report an error at the block before launching the renderer. +By default a renderer failure emits a warning and conversion continues with the error and diagram source in a listing. +Use `--fail-on-warnings` to keep that output and return status 1, or `-a diagram-on-error=abort` to stop at the failed block. +A document cannot supply an executable path. See the link:../extensions/diagram/README.adoc[diagram guide] for block syntax. + +Linked assets follow the `imagesdir` in effect at the block, relative to the converted file's directory. +Set `:imagesoutdir: staging` to write diagrams under `staging` relative to the working directory, including with `-o`. Links still use `imagesdir`, and embedding reads the staged files. +For stdout, relative links resolve from the working directory, including when reading stdin. +For a PDF document, pass `--pdf2svg` with `--lualatex` so TikZ produces an embeddable SVG. +Embedded HTML images and PDF image inputs resolve from the source directory (the working directory for stdin). +The terminal backend resolves images from the working directory, including in a pager. + Files, stdin, batches, terminal output, and pager output use the same pipeline. The selected backend supplies attributes before preprocessing, and every document gets fresh extension handlers. Library callers use @@ -515,6 +545,10 @@ echo '{"contents":"= Hello","path":"test.adoc","type":"block"}' \ | no | HTML terminal previews and session/replay rendering. +| `diagram` +| no +| Makes native diagram styles available through `--extension diagram` and caller-supplied tool paths. + | `terminal-emulator` | no | Ghostty-backed terminal session rendering; selects the terminal backend. diff --git a/acdc-cli/src/subcommands/convert.rs b/acdc-cli/src/subcommands/convert.rs index f3acb41df..3d897dfd0 100644 --- a/acdc-cli/src/subcommands/convert.rs +++ b/acdc-cli/src/subcommands/convert.rs @@ -37,6 +37,9 @@ mod selection; type RawAttributes<'a> = std::collections::HashMap, AttributeValue<'a>>; +mod extensions; +use extensions::Selection; + #[cfg(test)] #[path = "convert/pipeline_tests.rs"] mod pipeline_tests; @@ -70,6 +73,10 @@ pub(crate) struct Args { #[arg(long = "extension", value_name = "NAME", action = ArgAction::Append)] extensions: Vec, + #[cfg(feature = "diagram")] + #[command(flatten)] + diagram: Box, + /// Backend output format /// /// `html` is the default when its feature is compiled in; otherwise @@ -301,9 +308,7 @@ fn run_with_registries( .resolve(&args.backend, args.variant.as_deref()) .map_err(|e| error::display(&e))?; - let extensions = available - .select(&args.extensions) - .map_err(|error| error::display(&error))?; + let extensions = Selection::new(args, available, backend.asset_base)?; #[cfg(feature = "pdf")] validate_pdf_options(args, backend.pdf_options)?; @@ -329,7 +334,7 @@ fn run_with_registries( .build(); let document_attributes = build_parser_options(args, &options); - let summary = (backend.run)(args, &options, document_attributes, extensions.as_ref())?; + let summary = (backend.run)(args, &options, document_attributes, &extensions)?; if args.fail_on_warnings && summary.warning_count > 0 { let count = summary.warning_count; @@ -495,7 +500,7 @@ fn run_converter( args: &Args, base_options: &Options, document_attributes: OptionsBuilder<'static>, - extensions: Option<&Extensions>, + extensions: &Selection, make_converter: F, ) -> MietteResult where @@ -508,7 +513,7 @@ where let converter = configure_pipeline( make_converter(base_options.clone(), document_attributes) .map_err(|e| error::display(&e))?, - extensions, + extensions.for_input(None), ); let stdin = std::io::stdin(); let mut reader = BufReader::new(stdin.lock()); @@ -524,7 +529,7 @@ where let converter = configure_pipeline( make_converter(base_options.clone(), document_attributes) .map_err(|e| error::display(&e))?, - extensions, + extensions.for_input(Some(file)), ); let parse_result = if base_options.timings() { let now = Instant::now(); @@ -590,7 +595,7 @@ fn run_multi_file( base_options: &Options, document_attributes: &OptionsBuilder<'static>, files_to_process: &[PathBuf], - extensions: Option<&Extensions>, + extensions: &Selection, make_converter: F, ) -> MietteResult where @@ -625,7 +630,7 @@ where .map(|file| -> Result<_, P::Error> { let converter = configure_pipeline( make_converter(converter_options.clone(), document_attributes.clone())?, - extensions, + extensions.for_input(Some(file)), ); let entry = if show_timings { let now = Instant::now(); @@ -1155,7 +1160,7 @@ mod tests { &Options::default(), &ParserOptions::builder(), &files, - Some(&extension), + &Selection::Shared(Some(extension.clone())), acdc_converters_html::Converter::new, )?; assert_eq!(batch.output_paths.len(), 2); diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs new file mode 100644 index 000000000..260b3e9d6 --- /dev/null +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -0,0 +1,471 @@ +use acdc_converters_core::pipeline::{ExtensionCatalog, Extensions}; +#[cfg(feature = "diagram")] +use acdc_diagram::OutputDirectories; +#[cfg(feature = "diagram")] +use acdc_parser::extensions::{BlockMacro, BlockStyle, Registry, RegistryBuilder}; +use miette::Result; +use std::path::Path; + +use super::Args; +use crate::error; + +/// Directory the selected converter uses to resolve linked images. +#[derive(Clone, Copy)] +pub(super) enum AssetBase { + Output, + #[cfg(feature = "pdf")] + Source, + #[cfg(feature = "terminal")] + WorkingDirectory, +} + +#[derive(Debug)] +pub(super) enum Selection { + Shared(Option), + #[cfg(feature = "diagram")] + ByDirectory(std::collections::HashMap>), +} + +impl Selection { + pub(super) fn new( + args: &Args, + catalog: &ExtensionCatalog, + asset_base: AssetBase, + ) -> Result { + #[cfg(feature = "diagram")] + if args.extensions.iter().any(|name| name == "diagram") { + return args.diagram.select(args, catalog, asset_base); + } else if args.diagram.has_renderer() { + return Err(miette::miette!( + "diagram tool paths require --extension diagram" + )); + } + #[cfg(not(feature = "diagram"))] + let _ = asset_base; + catalog + .select(&args.extensions) + .map(Self::Shared) + .map_err(|e| error::display(&e)) + } + + pub(super) fn for_input(&self, input: Option<&Path>) -> Option<&Extensions> { + #[cfg(not(feature = "diagram"))] + let _ = input; + match self { + Self::Shared(selected) => selected.as_ref(), + #[cfg(feature = "diagram")] + Self::ByDirectory(dirs) => dirs.get(parent(input)).and_then(Option::as_ref), + } + } +} + +#[cfg(feature = "diagram")] +fn parent(file: Option<&Path>) -> &Path { + file.and_then(Path::parent) + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")) +} + +#[cfg(feature = "diagram")] +#[derive(clap::Args, Debug)] +pub(super) struct DiagramArgs { + /// Path to the trusted blockdiag renderer + #[arg(long, value_name = "PATH")] + blockdiag: Option, + /// Path to the trusted seqdiag renderer + #[arg(long, value_name = "PATH")] + seqdiag: Option, + /// Path to the trusted actdiag renderer + #[arg(long, value_name = "PATH")] + actdiag: Option, + /// Path to the trusted nwdiag renderer + #[arg(long, value_name = "PATH")] + nwdiag: Option, + /// Path to the trusted packetdiag renderer + #[arg(long, value_name = "PATH")] + packetdiag: Option, + /// Path to the trusted rackdiag renderer + #[arg(long, value_name = "PATH")] + rackdiag: Option, + /// Path to the trusted nomnoml renderer + #[arg(long, value_name = "PATH")] + nomnoml: Option, + /// Path to the trusted smcat renderer + #[arg(long, value_name = "PATH")] + smcat: Option, + /// Path to the trusted dbml-renderer renderer + #[arg(long, value_name = "PATH")] + dbml_renderer: Option, + /// Path to the trusted graphviz-py renderer + #[arg(long, value_name = "PATH")] + graphviz_py: Option, + /// Path to the trusted d2 renderer + #[arg(long, value_name = "PATH")] + d2: Option, + /// Path to the trusted shaape renderer + #[arg(long, value_name = "PATH")] + shaape: Option, + /// Path to the trusted symbolator renderer + #[arg(long, value_name = "PATH")] + symbolator: Option, + /// Path to the trusted pintora renderer + #[arg(long, value_name = "PATH")] + pintora: Option, + /// Path to the trusted a2s renderer + #[arg(long, value_name = "PATH")] + a2s: Option, + /// Path to the trusted svgbob renderer + #[arg(long, value_name = "PATH")] + svgbob: Option, + /// Path to the trusted syntrax renderer + #[arg(long, value_name = "PATH")] + syntrax: Option, + /// Path to the trusted diagrams-python renderer + #[arg(long, value_name = "PATH")] + diagrams_python: Option, + /// Path to the trusted ditaa renderer + #[arg(long, value_name = "PATH")] + ditaa: Option, + /// Path to the trusted vhs renderer + #[arg(long, value_name = "PATH")] + vhs: Option, + /// Path to the trusted gnuplot renderer + #[arg(long, value_name = "PATH")] + gnuplot: Option, + /// Path to the trusted umlet renderer + #[arg(long, value_name = "PATH")] + umlet: Option, + /// Path to the trusted bpmn-js renderer + #[arg(long, value_name = "PATH")] + bpmn_js: Option, + /// Path to the trusted mmdc renderer + #[arg(long, value_name = "PATH")] + mmdc: Option, + /// Path to the trusted oxdraw renderer + #[arg(long, value_name = "PATH")] + oxdraw: Option, + /// Path to the trusted lilypond renderer + #[arg(long, value_name = "PATH")] + lilypond: Option, + /// Path to the trusted erd renderer + #[arg(long, value_name = "PATH")] + erd: Option, + /// Path to the trusted roger renderer + #[arg(long, value_name = "PATH")] + roger: Option, + /// Path to the trusted plantuml renderer + #[arg(long, value_name = "PATH")] + plantuml: Option, + /// Vega PNG renderer + #[arg(long, value_name = "PATH", requires = "vg2svg")] + vg2png: Option, + /// Vega-Lite compiler + #[arg(long, value_name = "PATH", requires = "vg2svg")] + vl2vg: Option, + /// Path to the trusted vg2svg renderer + #[arg(long, value_name = "PATH")] + vg2svg: Option, + /// `ImageMagick` executable for captioned image macros + #[arg(long, value_name = "PATH")] + magick: Option, + /// Path to the trusted bytefield-svg executable + #[arg(long, value_name = "PATH")] + bytefield_svg: Option, + /// Path to the trusted `GoAT` ASCII diagram renderer + #[arg(long, value_name = "PATH")] + goat: Option, + /// Path to the trusted Pikchr executable + #[arg(long, value_name = "PATH")] + pikchr: Option, + /// Path to the trusted dpic executable for PIC diagrams + #[arg(long, value_name = "PATH")] + dpic: Option, + /// Path to the trusted Graphviz dot executable + #[arg(long, value_name = "PATH")] + graphviz_dot: Option, + /// Path to the trusted mscgen executable for message sequence charts + #[arg(long, value_name = "PATH")] + mscgen: Option, + /// Path to the trusted wavedrom-cli executable + #[arg(long, value_name = "PATH")] + wavedrom_cli: Option, + /// Path to the trusted lualatex executable + #[arg(long, value_name = "PATH")] + lualatex: Option, + /// Path to the trusted pdf2svg executable for SVG output + #[arg(long, value_name = "PATH", requires = "lualatex")] + pdf2svg: Option, +} + +#[cfg(feature = "diagram")] +impl DiagramArgs { + fn configured_renderers( + &self, + ) -> impl Iterator { + [ + (acdc_diagram::renderer::VEGALITE, self.vl2vg.as_deref()), + (acdc_diagram::renderer::VEGA, self.vg2svg.as_deref()), + (acdc_diagram::renderer::SALT, self.plantuml.as_deref()), + (acdc_diagram::renderer::PLANTUML, self.plantuml.as_deref()), + (acdc_diagram::renderer::PENROSE, self.roger.as_deref()), + (acdc_diagram::renderer::ERD, self.erd.as_deref()), + (acdc_diagram::renderer::LILYPOND, self.lilypond.as_deref()), + (acdc_diagram::renderer::OXDRAW, self.oxdraw.as_deref()), + (acdc_diagram::renderer::MERMAID, self.mmdc.as_deref()), + (acdc_diagram::renderer::BPMN, self.bpmn_js.as_deref()), + (acdc_diagram::renderer::UMLET, self.umlet.as_deref()), + (acdc_diagram::renderer::GNUPLOT, self.gnuplot.as_deref()), + (acdc_diagram::renderer::TAPE, self.vhs.as_deref()), + (acdc_diagram::renderer::DITAA, self.ditaa.as_deref()), + ( + acdc_diagram::renderer::DIAGRAMS, + self.diagrams_python.as_deref(), + ), + (acdc_diagram::renderer::SYNTRAX, self.syntrax.as_deref()), + (acdc_diagram::renderer::SVGBOB, self.svgbob.as_deref()), + (acdc_diagram::renderer::A2S, self.a2s.as_deref()), + (acdc_diagram::renderer::PINTORA, self.pintora.as_deref()), + ( + acdc_diagram::renderer::SYMBOLATOR, + self.symbolator.as_deref(), + ), + (acdc_diagram::renderer::SHAAPE, self.shaape.as_deref()), + (acdc_diagram::renderer::D2, self.d2.as_deref()), + ( + acdc_diagram::renderer::GRAPHVIZ_PY, + self.graphviz_py.as_deref(), + ), + (acdc_diagram::renderer::DBML, self.dbml_renderer.as_deref()), + (acdc_diagram::renderer::SMCAT, self.smcat.as_deref()), + (acdc_diagram::renderer::NOMNOML, self.nomnoml.as_deref()), + (acdc_diagram::renderer::RACKDIAG, self.rackdiag.as_deref()), + ( + acdc_diagram::renderer::PACKETDIAG, + self.packetdiag.as_deref(), + ), + (acdc_diagram::renderer::NWDIAG, self.nwdiag.as_deref()), + (acdc_diagram::renderer::ACTDIAG, self.actdiag.as_deref()), + (acdc_diagram::renderer::SEQDIAG, self.seqdiag.as_deref()), + (acdc_diagram::renderer::BLOCKDIAG, self.blockdiag.as_deref()), + ] + .into_iter() + .filter_map(|(renderer, path): (_, Option<&Path>)| path.map(|p| (renderer, p))) + } + + fn register_configured( + &self, + registry: &mut RegistryBuilder, + output: OutputDirectories<'_>, + ) -> Result<()> { + let companions: Vec<_> = [ + ("vg2svg", self.vg2svg.as_deref()), + ("vg2png", self.vg2png.as_deref()), + ("vl2vg", self.vl2vg.as_deref()), + ("dot", self.graphviz_dot.as_deref()), + ] + .into_iter() + .filter_map(|(name, path)| path.map(|p| (name, p))) + .collect(); + for (renderer, tool) in self.configured_renderers() { + let (style, file) = renderer + .processors_with_tools(tool, output, &companions) + .map_err(|e| miette::miette!("cannot configure {}: {e}", tool.display()))?; + registry + .register_block_style(style) + .map_err(|e| error::display(&e))?; + registry.register(file).map_err(|e| error::display(&e))?; + } + Ok(()) + } + + fn has_renderer(&self) -> bool { + self.wavedrom_cli.is_some() + || self.lualatex.is_some() + || self.graphviz_dot.is_some() + || self.mscgen.is_some() + || self.dpic.is_some() + || self.pikchr.is_some() + || self.goat.is_some() + || self.magick.is_some() + || self.bytefield_svg.is_some() + || self.configured_renderers().next().is_some() + } + + fn select( + &self, + args: &Args, + catalog: &ExtensionCatalog, + asset_base: AssetBase, + ) -> Result { + use std::collections::{HashMap, hash_map::Entry}; + if !self.has_renderer() { + return Err(miette::miette!( + "--extension diagram requires at least one renderer executable (see acdc convert --help)" + )); + } + // The terminal backend displays files from the working directory, including in a pager. + #[cfg(feature = "terminal")] + if matches!(asset_base, AssetBase::WorkingDirectory) { + let cwd = Path::new("."); + return self + .register(args, catalog, cwd, cwd) + .map(Selection::Shared); + } + + let select = |source: &Path| { + let linked = match args.out_file.as_deref() { + Some("-") => Path::new("."), + Some(file) => parent(Some(Path::new(file))), + None => source, + }; + // PDF reads ordinary image nodes relative to the source, even with -o. + #[cfg(feature = "pdf")] + let linked = if matches!(asset_base, AssetBase::Source) { + source + } else { + linked + }; + #[cfg(not(any(feature = "terminal", feature = "pdf")))] + let _ = asset_base; + self.register(args, catalog, linked, source) + }; + + if args.out_file.is_some() || args.files.len() <= 1 { + return select(parent(args.files.first().map(std::path::PathBuf::as_path))) + .map(Selection::Shared); + } + let mut dirs = HashMap::new(); + for file in &args.files { + let dir = parent(Some(file)); + if let Entry::Vacant(entry) = dirs.entry(dir.to_owned()) { + entry.insert(select(dir)?); + } + } + Ok(Selection::ByDirectory(dirs)) + } + + fn register( + &self, + args: &Args, + available: &ExtensionCatalog, + linked: &Path, + embedded: &Path, + ) -> Result> { + let output = + OutputDirectories::new(linked, embedded).with_imagesoutdir_base(Path::new(".")); + let mut registry = Registry::builder(); + if let Some(tool) = &self.graphviz_dot { + register_file_renderer( + &mut registry, + "Graphviz", + tool, + output, + acdc_diagram::graphviz, + acdc_diagram::graphviz_file, + )?; + } + if let Some(tool) = &self.mscgen { + register_file_renderer( + &mut registry, + "mscgen", + tool, + output, + acdc_diagram::msc, + acdc_diagram::msc_file, + )?; + } + if let Some(tool) = &self.dpic { + register_file_renderer( + &mut registry, + "dpic", + tool, + output, + acdc_diagram::dpic, + acdc_diagram::dpic_file, + )?; + } + if let Some(tool) = &self.pikchr { + register_file_renderer( + &mut registry, + "pikchr", + tool, + output, + acdc_diagram::pikchr, + acdc_diagram::pikchr_file, + )?; + } + if let Some(tool) = &self.goat { + register_file_renderer( + &mut registry, + "goat", + tool, + output, + acdc_diagram::goat, + acdc_diagram::goat_file, + )?; + } + if let Some(tool) = &self.bytefield_svg { + register_file_renderer( + &mut registry, + "bytefield-svg", + tool, + output, + acdc_diagram::bytefield, + acdc_diagram::bytefield_file, + )?; + } + if let Some(tool) = &self.wavedrom_cli { + let style = acdc_diagram::wavedrom(tool, output).map_err(|e| { + miette::miette!("cannot configure WaveDrom with {}: {e}", tool.display()) + })?; + registry + .register_block_style(style) + .map_err(|e| error::display(&e))?; + } + if let Some(tool) = &self.lualatex { + let style = acdc_diagram::tikz(tool, self.pdf2svg.as_deref(), output).map_err(|e| { + miette::miette!("cannot configure TikZ with {}: {e}", tool.display()) + })?; + registry + .register_block_style(style) + .map_err(|e| error::display(&e))?; + } + self.register_configured(&mut registry, output)?; + if let Some(tool) = &self.magick { + let descriptor = acdc_diagram::meme(tool, output) + .map_err(|e| miette::miette!("cannot configure ImageMagick: {e}"))?; + registry + .register(descriptor) + .map_err(|e| error::display(&e))?; + } + let mut catalog = available.clone(); + catalog + .register("diagram", registry.build()) + .map_err(|e| error::display(&e))?; + catalog + .select(&args.extensions) + .map_err(|e| error::display(&e)) + } +} + +#[cfg(feature = "diagram")] +fn register_file_renderer<'a>( + registry: &mut RegistryBuilder, + name: &str, + tool: &Path, + output: OutputDirectories<'a>, + style: impl FnOnce(&Path, OutputDirectories<'a>) -> std::io::Result, + file_macro: impl FnOnce(&Path, OutputDirectories<'a>) -> std::io::Result, +) -> Result<()> { + let configure = + |e: std::io::Error| miette::miette!("cannot configure {name} with {}: {e}", tool.display()); + let style = style(tool, output).map_err(configure)?; + let file_macro = file_macro(tool, output).map_err(configure)?; + registry + .register_block_style(style) + .map_err(|e| error::display(&e))?; + registry + .register(file_macro) + .map_err(|e| error::display(&e))?; + Ok(()) +} diff --git a/acdc-cli/src/subcommands/convert/selection.rs b/acdc-cli/src/subcommands/convert/selection.rs index 658ad2aa5..e1cdfb471 100644 --- a/acdc-cli/src/subcommands/convert/selection.rs +++ b/acdc-cli/src/subcommands/convert/selection.rs @@ -7,32 +7,29 @@ use clap::builder::{ }; use super::{ - Args, ConversionSummary, Extensions, MietteResult, Options, OptionsBuilder, error, - run_converter, + Args, ConversionSummary, MietteResult, Options, OptionsBuilder, Selection, error, + extensions::AssetBase, run_converter, }; -type Run = dyn Fn( - &Args, - &Options, - OptionsBuilder<'static>, - Option<&Extensions>, - ) -> MietteResult +type Run = dyn Fn(&Args, &Options, OptionsBuilder<'static>, &Selection) -> MietteResult + Send + Sync; pub(super) struct Runner { pub(super) run: Box, + pub(super) asset_base: AssetBase, #[cfg(feature = "pdf")] pub(super) pdf_options: bool, } impl Runner { fn new( + asset_base: AssetBase, run: impl Fn( &Args, &Options, OptionsBuilder<'static>, - Option<&Extensions>, + &Selection, ) -> MietteResult + Send + Sync @@ -40,6 +37,7 @@ impl Runner { ) -> Self { Self { run: Box::new(run), + asset_base, #[cfg(feature = "pdf")] pdf_options: false, } @@ -52,7 +50,7 @@ impl Runner { P::Error: Send + 'static, F: Fn(Options, OptionsBuilder<'static>) -> Result + Send + Sync + 'static, { - Self::new(move |args, opts, parser, extensions| { + Self::new(AssetBase::Output, move |args, opts, parser, extensions| { run_converter(args, opts, parser, extensions, &factory) }) } @@ -82,17 +80,20 @@ pub(super) fn builtins() -> Result, SelectionError> { })?; #[cfg(feature = "terminal")] backends.register(acdc_converters_terminal::REGISTRATION, |()| { - Runner::new(|args, options, parser, extensions| { - super::run_terminal_with_pager(args, options, parser, extensions) - .map_err(|e| error::display(&e)) - }) + Runner::new( + AssetBase::WorkingDirectory, + |args, options, parser, extensions| { + super::run_terminal_with_pager(args, options, parser, extensions.for_input(None)) + .map_err(|e| error::display(&e)) + }, + ) })?; #[cfg(feature = "pdf")] backends.register(acdc_converters_pdf::REGISTRATION, |()| { let run = |args: &Args, options: &Options, parser: OptionsBuilder<'static>, - extensions: Option<&Extensions>| { + extensions: &Selection| { let pdf_options = super::pdf_options_from_args(args); run_converter(args, options, parser, extensions, move |opts, attrs| { acdc_converters_pdf::Converter::new(opts, attrs) @@ -102,6 +103,7 @@ pub(super) fn builtins() -> Result, SelectionError> { Runner { run: Box::new(run), pdf_options: true, + asset_base: AssetBase::Source, } })?; Ok(backends) diff --git a/acdc-cli/tests/cli.rs b/acdc-cli/tests/cli.rs index 5f051d521..3db07f209 100644 --- a/acdc-cli/tests/cli.rs +++ b/acdc-cli/tests/cli.rs @@ -1,3 +1,7 @@ +#[cfg(feature = "html")] +#[path = "convert/diagram.rs"] +mod diagram; + use std::{ error::Error, io::{self, Write}, diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs new file mode 100644 index 000000000..b84e4771d --- /dev/null +++ b/acdc-cli/tests/convert/diagram.rs @@ -0,0 +1,1811 @@ +use super::{output_text, run_acdc_in}; +use std::error::Error; + +type TestResult = Result<(), Box>; +const SOURCE: &str = ":imagesdir: images\n\n[wavedrom,clock,svg]\n....\nwave body\n....\n"; + +#[test] +fn diagrams_require_explicit_activation() -> TestResult { + let dir = tempfile::tempdir()?; + let output = run_acdc_in( + dir.path(), + &["convert", "--stdin", "--embedded"], + Some(SOURCE), + )?; + assert!(output.status.success(), "{}", output_text(&output.stderr)); + assert!(output_text(&output.stdout).contains("wave body")); + assert!(!dir.path().join("images").exists()); + Ok(()) +} + +#[cfg(not(feature = "diagram"))] +#[test] +fn diagram_is_unavailable_before_input_is_read() -> TestResult { + let dir = tempfile::tempdir()?; + let output = run_acdc_in( + dir.path(), + &["convert", "--extension", "diagram", "missing.adoc"], + None, + )?; + assert!(!output.status.success()); + assert!(output_text(&output.stderr).contains("extension `diagram` is not available")); + Ok(()) +} + +#[cfg(feature = "diagram")] +#[test] +fn diagram_configuration_requires_activation_and_tools() -> TestResult { + let dir = tempfile::tempdir()?; + for (args, expected) in [ + ( + vec!["--extension", "diagram"], + "requires at least one renderer executable", + ), + ( + vec!["--bytefield-svg", "missing"], + "require --extension diagram", + ), + (vec!["--goat", "missing"], "require --extension diagram"), + (vec!["--pikchr", "missing"], "require --extension diagram"), + (vec!["--dpic", "missing"], "require --extension diagram"), + (vec!["--mscgen", "missing"], "require --extension diagram"), + ( + vec!["--graphviz-dot", "missing"], + "require --extension diagram", + ), + ( + vec!["--wavedrom-cli", "missing"], + "require --extension diagram", + ), + ( + vec!["--extension", "diagram", "--pdf2svg", "missing"], + "--lualatex", + ), + ] { + let mut command = vec!["convert", "missing.adoc"]; + command.extend(args); + let output = run_acdc_in(dir.path(), &command, None)?; + assert!(!output.status.success()); + assert!( + output_text(&output.stderr).contains(expected), + "{}", + output_text(&output.stderr) + ); + } + Ok(()) +} + +#[cfg(all(feature = "diagram", unix))] +mod active { + use super::*; + use std::{fs, os::unix::fs::PermissionsExt, path::Path, process::Output}; + + fn setup(root: &Path) -> TestResult { + fs::write( + root.join("renderer"), + "#!/bin/sh\nprintf '%s' '' > \"$4\"\n", + )?; + fs::set_permissions(root.join("renderer"), fs::Permissions::from_mode(0o700))?; + Ok(()) + } + + fn convert(root: &Path, args: &[&str], stdin: Option<&str>) -> std::io::Result { + let mut command = vec![ + "convert", + "--extension", + "diagram", + "--wavedrom-cli", + "./renderer", + "--fail-on-warnings", + ]; + command.extend(args); + run_acdc_in(root, &command, stdin) + } + + #[test] + fn blockdiag_block_and_file() -> TestResult { + tool_sample( + "blockdiag", + "--blockdiag", + "blockdiag { API -> DB; }", + "svg", + r#"test "$1" = -a +test "$2" = -o +test "$4" = -Tsvg +test "$5" = - +test "$(cat)" = "$(cat chart.source)" +printf '%s' '' > "$3""#, + ) + } + + #[test] + fn seqdiag_block_and_file() -> TestResult { + tool_sample( + "seqdiag", + "--seqdiag", + "seqdiag { API -> DB; }", + "svg", + r#"test "$1" = -a +test "$2" = -o +test "$4" = -Tsvg +test "$5" = - +test "$(cat)" = "$(cat chart.source)" +printf '%s' '' > "$3""#, + ) + } + + #[test] + fn actdiag_block_and_file() -> TestResult { + tool_sample( + "actdiag", + "--actdiag", + "actdiag { start -> finish; }", + "svg", + r#"test "$1" = -a +test "$2" = -o +test "$4" = -Tsvg +test "$5" = - +test "$(cat)" = "$(cat chart.source)" +printf '%s' '' > "$3""#, + ) + } + + #[test] + fn nwdiag_block_and_file() -> TestResult { + tool_sample( + "nwdiag", + "--nwdiag", + "nwdiag { network lan { API; DB; } }", + "svg", + r#"test "$1" = -a +test "$2" = -o +test "$4" = -Tsvg +test "$5" = - +test "$(cat)" = "$(cat chart.source)" +printf '%s' '' > "$3""#, + ) + } + + #[test] + fn packetdiag_block_and_file() -> TestResult { + tool_sample( + "packetdiag", + "--packetdiag", + "packetdiag { 0-7: Type; 8-15: Size; }", + "svg", + r#"test "$1" = -a +test "$2" = -o +test "$4" = -Tsvg +test "$5" = - +test "$(cat)" = "$(cat chart.source)" +printf '%s' '' > "$3""#, + ) + } + + #[test] + fn rackdiag_block_and_file() -> TestResult { + tool_sample( + "rackdiag", + "--rackdiag", + "rackdiag { rack { 1: API; 2: DB; } }", + "svg", + r#"test "$1" = -a +test "$2" = -o +test "$4" = -Tsvg +test "$5" = - +test "$(cat)" = "$(cat chart.source)" +printf '%s' '' > "$3""#, + ) + } + + #[test] + fn nomnoml_block_and_file() -> TestResult { + tool_sample( + "nomnoml", + "--nomnoml", + "[Client] -> [Server]", + "svg", + r#"test "$#" = 2 +test "$(cat "$1")" = "$(cat chart.source)" +printf '%s' '' > "$2""#, + ) + } + + #[test] + fn smcat_block_and_file() -> TestResult { + tool_sample( + "smcat", + "--smcat", + "idle => active;", + "svg", + r#"test "$1:$3:$4:$5" = "-o:-T:svg:-" +test "$(cat)" = "$(cat chart.source)" +printf '%s' '' > "$2""#, + ) + } + + #[test] + fn dbml_block_and_file() -> TestResult { + tool_sample( + "dbml", + "--dbml-renderer", + "Table users {\n id int [pk]\n}", + "svg", + r#"test "$#" = 0 +test "$(cat)" = "$(cat chart.source)" +printf '%s' '' "#, + ) + } + + #[test] + fn graphviz_py_block_and_file() -> TestResult { + tool_sample( + "graphviz_py", + "--graphviz-py", + "digraph { A -> B }", + "svg", + r#"test "$2" = -Tsvg +test "$(cat)" = "$(cat chart.source)" +printf '%s' '' > "${1#-o}""#, + ) + } + + #[test] + fn d2_block_and_file() -> TestResult { + tool_sample( + "d2", + "--d2", + "API -> DB", + "svg", + r#"test "$1:$2:$3" = "--browser:false:-" +test "$(cat)" = "$(cat chart.source)" +printf '%s' '' > "$4""#, + ) + } + + #[test] + fn shaape_block_and_file() -> TestResult { + tool_sample( + "shaape", + "--shaape", + "+---+\n| A |\n+---+", + "svg", + r#"test "$1:$3:$4:$5" = "-o:-t:svg:-" +test "$(cat)" = "$(cat chart.source)" +printf '%s' '' > "$2""#, + ) + } + + #[test] + fn symbolator_block_and_file() -> TestResult { + tool_sample( + "symbolator", + "--symbolator", + "entity Gate is\n port(a : in bit; q : out bit);\nend Gate;", + "svg", + r#"test "$1:$3" = "-i-:-fsvg" +test "$(cat)" = "$(cat chart.source)" +printf '%s' '' > "${2#-o}""#, + ) + } + + #[test] + fn pintora_block_and_file() -> TestResult { + tool_sample( + "pintora", + "--pintora", + "sequenceDiagram\nA->>B: hello", + "svg", + r#"test "$1:$2:$4" = "render:-i:-o" +test "$(cat "$3")" = "$(cat chart.source)" +printf '%s' '' > "$5""#, + ) + } + + #[test] + fn a2s_block_and_file() -> TestResult { + tool_sample( + "a2s", + "--a2s", + "+---+\n| A |\n+---+", + "svg", + r#"test "$1" = "-o" +cmp - chart.source +printf '%s' '' > "$2""#, + ) + } + + #[test] + fn svgbob_block_and_file() -> TestResult { + tool_sample( + "svgbob", + "--svgbob", + "+---+\n| A |\n+---+", + "svg", + r#"test "$1" = "-o" +test "$(cat)" = "$(cat chart.source)" +printf '%s' '' > "$2""#, + ) + } + + #[test] + fn syntrax_block_and_file() -> TestResult { + tool_sample( + "syntrax", + "--syntrax", + "line(\"term\", \"operator\", \"term\")", + "svg", + r#"test "$1:$3" = "-i:-o" +test "$(cat "$2")" = "$(cat chart.source)" +printf '%s' '' > "$4""#, + ) + } + + #[test] + fn diagrams_block_and_file() -> TestResult { + tool_sample( + "diagrams", + "--diagrams-python", + "from diagrams import Diagram, Node\nwith Diagram(\"Pipeline\", show=False):\n Node(\"Input\") >> Node(\"Output\")", + "svg", + r#"test "$1:$4" = "-c:svg" +test "$(cat)" = "$(cat chart.source)" +printf '%s' '' > "$3.svg""#, + ) + } + + #[test] + fn ditaa_block_and_file() -> TestResult { + tool_sample( + "ditaa", + "--ditaa", + "+---+\n| A |\n+---+", + "svg", + r#"test "$3" = "--svg" +test "$(cat "$1")" = "$(cat chart.source)" +printf '%s' '' > "$2""#, + ) + } + + #[test] + fn tape_block_and_file() -> TestResult { + tool_sample( + "tape", + "--vhs", + "Type \"hello\"\nSleep 50ms", + "svg", + r#"test "$2" = "-o" +test "$(cat "$1")" = "$(cat chart.source)" +printf '%s' '' > "$3""#, + ) + } + + #[test] + fn gnuplot_block_and_file() -> TestResult { + tool_sample( + "gnuplot", + "--gnuplot", + "plot sin(x)", + "svg", + r#"test "$#" = 0 +grep -Fx "set term svg" >/dev/null +printf '%s' '' "#, + ) + } + + #[test] + fn umlet_block_and_file() -> TestResult { + tool_sample( + "umlet", + "--umlet", + "10", + "svg", + r#"test "$1:$2" = "-action=convert:-format=svg" +test "$(cat "${3#-filename=}")" = "$(cat chart.source)" +printf '%s\n' "" > "${4#-output=}" +printf '%s' '' >> "${4#-output=}""#, + ) + } + + #[test] + fn bpmn_block_and_file() -> TestResult { + tool_sample( + "bpmn", + "--bpmn-js", + "", + "svg", + r#"test "$2:$4:$5" = "-o:-t:svg" +test "$(cat "$1")" = "$(cat chart.source)" +printf '%s' '' > "$3""#, + ) + } + + #[test] + fn mermaid_block_and_file() -> TestResult { + tool_sample( + "mermaid", + "--mmdc", + "graph TD\n A --> B", + "svg", + r#"test "$1:$3" = "-i:-o" +test "$(cat "$2")" = "$(cat chart.source)" +printf '%s' '' > "$4""#, + ) + } + + #[test] + fn oxdraw_block_and_file() -> TestResult { + tool_sample( + "oxdraw", + "--oxdraw", + "graph TD\n A --> B", + "svg", + r#"test "$1:$2:$3:$5:$6:$7" = "--input:-:--output:--output-format:svg:--quiet" +test "$(cat)" = "$(cat chart.source)" +printf '%s' '' > "$4""#, + ) + } + + #[test] + fn lilypond_block_and_file() -> TestResult { + tool_sample( + "lilypond", + "--lilypond", + "\\relative c' { c d e f }", + "pdf", + r#"test "$5:$7:$8" = "-o:-f:pdf" +grep -F 'oddFooterMarkup=##f' >/dev/null +printf '%%PDF-1.7 +%%%%EOF +' > "$6.cropped.pdf""#, + ) + } + + #[test] + fn erd_block_and_file() -> TestResult { + tool_sample_with( + "erd", + "--erd", + "[Person]\nname {label: \"text\"}", + "svg", + r#"test "$1:$3:$4" = "-o:-f:dot" +test "$(cat)" = "$(cat chart.source)" +printf '%s' 'digraph { A -> B }' > "$2""#, + "", + &[( + "--graphviz-dot", + "./dot", + r#"test "$2" = -Tsvg +grep -F 'digraph' >/dev/null +printf '%s' '' > "${1#-o}""#, + )], + ) + } + + #[test] + fn penrose_block_and_file() -> TestResult { + tool_sample_with( + "penrose", + "--roger", + "Set A", + "svg", + r#"test "$1:$2:$4:$5:$6" = "trio:-o:--path:/:--trio" +test "$(cat "$7")" = "$(cat chart.source)" +printf '%s' '' > "$3""#, + ":penrose-domain_file: types.domain\n:penrose-style_file: layout.style\n", + &[], + ) + } + + #[test] + fn plantuml_block_and_file() -> TestResult { + tool_sample( + "plantuml", + "--plantuml", + "Alice -> Bob: hello", + "svg", + r#"grep -F '@startuml' >/dev/null +printf '%s' '' "#, + ) + } + + #[test] + fn salt_block_and_file() -> TestResult { + tool_sample( + "salt", + "--plantuml", + "{\n[OK]\n}", + "svg", + r#"grep -F '@startsalt' >/dev/null +printf '%s' '' "#, + ) + } + + #[test] + fn vega_block_and_file() -> TestResult { + tool_sample( + "vega", + "--vg2svg", + "{\"width\":64,\"height\":32,\"marks\":[]}", + "svg", + r#"test "$1:$3" = "--base:--header" +test "$(cat)" = "$(cat chart.source)" +printf '%s' '' "#, + ) + } + + #[test] + fn vegalite_block_and_file() -> TestResult { + tool_sample_with( + "vegalite", + "--vl2vg", + "{\"mark\":\"point\",\"data\":{\"values\":[{\"x\":1}]}}", + "svg", + r#"test "$#" = 0 +cat"#, + "", + &[( + "--vg2svg", + "./vg2svg", + r#"test "$1:$3" = "--base:--header" +cat >/dev/null +printf '%s' '' "#, + )], + ) + } + + #[test] + fn meme_block_and_file() -> TestResult { + let temp = tempfile::tempdir()?; + let root = temp.path(); + fs::write(root.join("photo.jpg"), [0xff, 0xd8, 0xff, 0xd9])?; + fs::write( + root.join("doc.adoc"), + ".Caption\nmeme::photo.jpg[Mixed // case,Bottom,caption,gif,opts=noupcase,font=Sample]", + )?; + fs::write( + root.join("renderer"), + r#"#!/bin/sh +set -eu +for last; do :; done +case "$last" in + info:) printf '100 50';; + */top.png) + test "${10}" = Sample + printf '%s\n' "$@" > top-args + touch "$last";; + */bottom.png) touch "$last";; + */output.gif) + test "$2" != '' + printf 'GIF89a\001\000\001\000\200\000\000\000\000\000\377\377\377\054\000\000\000\000\001\000\001\000\000\002\002\104\001\000\073' > "$last";; + *) exit 1;; +esac +"#, + )?; + fs::set_permissions(root.join("renderer"), fs::Permissions::from_mode(0o700))?; + let args = [ + "convert", + "--extension", + "diagram", + "--magick", + "./renderer", + "--fail-on-warnings", + "doc.adoc", + ]; + let run = run_acdc_in(root, &args, None)?; + assert!(run.status.success(), "{}", output_text(&run.stderr)); + let html = fs::read_to_string(root.join("doc.html"))?; + assert!(html.contains(r#"src="caption.gif""#)); + assert!(html.contains("Figure 1. Caption")); + assert!(fs::read_to_string(root.join("top-args"))?.contains("label:Mixed\ncase")); + Ok(()) + } + + #[test] + fn renderer_aliases_and_file_image_dimensions() -> TestResult { + let temp = tempfile::tempdir()?; + let root = temp.path(); + fs::write(root.join("chart.source"), "diagram text")?; + fs::write( + root.join("doc.adoc"), + "= Charts\n:svgbob-option-scale: 3\n\n[svgbob,scaled,SVG]\n----\nexample\n----\n\nsvgbob::chart.source[LiTeRaL]\n\nbpmn::chart.source[svg,width=37,height=12]", + )?; + fs::write( + root.join("renderer"), + r#"#!/bin/sh +set -eu +case "$1" in + -o) test "$3:$4" = "--scale:3"; file=$2;; + *.bpmn) test "$2" = "-o"; file=$3;; + *) exit 1;; +esac +printf '%s' '' > "$file" +"#, + )?; + fs::set_permissions(root.join("renderer"), fs::Permissions::from_mode(0o700))?; + let result = run_acdc_in( + root, + &[ + "convert", + "--extension", + "diagram", + "--svgbob", + "./renderer", + "--bpmn-js", + "./renderer", + "--fail-on-warnings", + "doc.adoc", + ], + None, + )?; + assert!(result.status.success(), "{}", output_text(&result.stderr)); + let html = fs::read_to_string(root.join("doc.html"))?; + assert!(html.contains("diagram text")); + assert!( + html.contains(r#"src="scaled.svg" alt="scaled" width="16" height="8""#), + "{html}" + ); + let image = html + .lines() + .find(|line| line.contains(r#"src="chart.svg""#)) + .ok_or("missing file macro image")?; + assert!( + image.contains(r#"width="37""#) && image.contains(r#"height="12""#), + "{image}" + ); + Ok(()) + } + + fn tool_sample( + style: &str, + flag: &str, + body: &str, + format: &str, + renderer: &str, + ) -> TestResult { + tool_sample_with(style, flag, body, format, renderer, "", &[]) + } + + fn tool_sample_with( + style: &str, + flag: &str, + body: &str, + format: &str, + renderer: &str, + header: &str, + companions: &[(&str, &str, &str)], + ) -> TestResult { + let temp = tempfile::tempdir()?; + let root = temp.path(); + fs::write(root.join("chart.source"), body)?; + fs::write( + root.join("doc.adoc"), + format!( + "{header}\n[{style},example,{format}]\n----\n{body}\n----\n\n.File\n{style}::chart.source[{format},alt=Chart]" + ), + )?; + fs::write( + root.join("renderer"), + format!("#!/bin/sh\nset -eu\n{renderer}\n"), + )?; + fs::set_permissions(root.join("renderer"), fs::Permissions::from_mode(0o700))?; + let mut args = vec![ + "convert", + "--extension", + "diagram", + flag, + "./renderer", + "--fail-on-warnings", + "doc.adoc", + ]; + for &(flag, path, script) in companions { + fs::write(root.join(path), format!("#!/bin/sh\nset -eu\n{script}\n"))?; + fs::set_permissions(root.join(path), fs::Permissions::from_mode(0o700))?; + args.extend([flag, path]); + } + let run = run_acdc_in(root, &args, None)?; + assert!(run.status.success(), "{}", output_text(&run.stderr)); + let html = fs::read_to_string(root.join("doc.html"))?; + for target in ["example", "chart"] { + assert!(root.join(format!("{target}.{format}")).is_file()); + assert!(html.contains(&format!(r#"src="{target}.{format}""#))); + } + assert!(html.contains("Figure 1. File")); + Ok(()) + } + + #[test] + fn bytefield_sends_block_and_file_source_to_stdin_and_publishes_svg() -> TestResult { + let temp = tempfile::tempdir()?; + let root = temp.path(); + fs::create_dir(root.join("fields"))?; + fs::write(root.join("expected-block.edn"), "(draw-box \"Header\")\n")?; + fs::write(root.join("fields/payload.edn"), "(draw-box \"Payload\")")?; + fs::write( + root.join("doc.adoc"), + "= Packet\n:imagesdir: images\n\n[bytefield,header]\n....\n(draw-box \"Header\")\n....\n\n.Payload layout\nbytefield::fields/payload.edn[svg,alt=Bytes]", + )?; + fs::write( + root.join("renderer"), + r#"#!/bin/sh +set -eu +test "$#" = 2 +test "$1" = --output +if test -f payload.edn; then + cmp - payload.edn +else + cmp - expected-block.edn +fi +printf '%s' '' > "$2" +"#, + )?; + fs::set_permissions(root.join("renderer"), fs::Permissions::from_mode(0o700))?; + let args = [ + "convert", + "--extension", + "diagram", + "--bytefield-svg", + "./renderer", + "--fail-on-warnings", + "doc.adoc", + ]; + let run = run_acdc_in(root, &args, None)?; + assert!(run.status.success(), "{}", output_text(&run.stderr)); + let html = fs::read_to_string(root.join("doc.html"))?; + for (target, alt) in [("header", "header"), ("payload", "Bytes")] { + assert!(html.contains(&format!( + r#"src="images/{target}.svg" alt="{alt}" width="80" height="24""# + ))); + assert!(root.join(format!("images/{target}.svg")).is_file()); + } + assert!(html.contains("Figure 1. Payload layout")); + Ok(()) + } + + #[test] + fn bytefield_rejects_renderer_overrides_and_recovers_from_failure() -> TestResult { + let temp = tempfile::tempdir()?; + let root = temp.path(); + fs::write(root.join("layout.edn"), "(draw-box \"Type\")")?; + fs::write( + root.join("renderer"), + "#!/bin/sh\nprintf '%s' partial > \"$2\"\nexit 7\n", + )?; + fs::set_permissions(root.join("renderer"), fs::Permissions::from_mode(0o700))?; + fs::write(root.join("layout.svg"), "previous image")?; + for (source, expected) in [ + ("bytefield::layout.edn[png]", "unsupported bytefield format"), + ( + "bytefield::layout.edn[bytefield-svg=other]", + "set the bytefield-svg executable", + ), + ( + ":bytefield-svg: other\n\n[bytefield]\n----\n(draw-box)\n----", + "set the bytefield-svg executable", + ), + ("bytefield::layout.edn[]", "bytefield-svg exited"), + ] { + fs::write(root.join("doc.adoc"), source)?; + let run = run_acdc_in( + root, + &[ + "convert", + "--extension", + "diagram", + "--bytefield-svg", + "./renderer", + "--fail-on-warnings", + "doc.adoc", + ], + None, + )?; + assert!(!run.status.success()); + assert!( + output_text(&run.stderr).contains(expected), + "{}", + output_text(&run.stderr) + ); + assert_eq!( + fs::read_to_string(root.join("layout.svg"))?, + "previous image" + ); + } + Ok(()) + } + + #[test] + fn goat_streams_ascii_and_applies_color_schemes_to_blocks_and_files() -> TestResult { + let temp = tempfile::tempdir()?; + let root = temp.path(); + fs::create_dir(root.join("charts"))?; + fs::write(root.join("charts/flow.txt"), " A -> B\n")?; + fs::write( + root.join("doc.adoc"), + "= GoAT +:goat-svg-color-dark-scheme: white +:goat-svg-color-light-scheme: navy + +[goat] +---- + A -> B +---- + +[goat,svg-color-dark-scheme=gray] +.... + A -> B +.... + +.External +goat::charts/flow.txt[svg,alt=Route,svg-color-light-scheme=maroon] +", + )?; + fs::write( + root.join("goat"), + r#"#!/bin/sh +set -eu +test "$#" -eq 4 +test "$1" = -sds +test "$3" = -sls +if test -f flow.txt; then + cmp - flow.txt + test "$2:$4" = white:maroon +else + cmp - charts/flow.txt + test "$4" = navy +fi +printf '%s:%s' "$2" "$4" +"#, + )?; + fs::set_permissions(root.join("goat"), fs::Permissions::from_mode(0o700))?; + let args = [ + "convert", + "--extension", + "diagram", + "--goat", + "./goat", + "--fail-on-warnings", + "doc.adoc", + ]; + let run = run_acdc_in(root, &args, None)?; + assert!(run.status.success(), "{}", output_text(&run.stderr)); + let html = fs::read_to_string(root.join("doc.html"))?; + assert!(html.contains("Figure 1. External")); + assert!(html.contains(r#"src="flow.svg" alt="Route" width="32" height="16""#)); + let mut images = Vec::new(); + for entry in fs::read_dir(root)? { + let entry = entry?; + let name = entry.file_name(); + let name = name.to_string_lossy(); + if name.starts_with("goat-") && name.ends_with(".svg") { + assert!(html.contains(&format!(r#"src="{name}""#))); + images.push(fs::read_to_string(entry.path())?); + } + } + assert_eq!(images.len(), 2); + for palette in ["gray:navy", "white:navy"] { + assert!(images.iter().any(|svg| svg.contains(palette))); + } + let previous = fs::read(root.join("flow.svg"))?; + for (source, expected) in [ + ("goat::charts/flow.txt[png]", "unsupported goat format"), + ( + "goat::charts/flow.txt[goat=other]", + "set the goat executable", + ), + ] { + fs::write(root.join("doc.adoc"), source)?; + let run = run_acdc_in(root, &args, None)?; + assert!(!run.status.success()); + assert!(output_text(&run.stderr).contains(expected)); + assert_eq!(fs::read(root.join("flow.svg"))?, previous); + } + Ok(()) + } + + #[test] + fn pikchr_renders_verbatim_blocks_and_file_macros_with_svg_only() -> TestResult { + let dir = tempfile::tempdir()?; + let root = dir.path(); + fs::create_dir(root.join("charts"))?; + fs::write(root.join("charts/flow.pikchr"), "box \"File\"")?; + fs::write( + root.join("doc.adoc"), + "= Charts\n:imagesdir: images\n\n[pikchr,diagram]\n....\nbox \"Block\"\n....\n\n.External\npikchr::charts/flow.pikchr[svg,alt=Flow]", + )?; + fs::write( + root.join("pikchr"), + r#"#!/bin/sh +set -eu +test "$#" = 2 +test "$1" = --svg-only +if test -f flow.pikchr; then + cmp "$2" flow.pikchr +else + printf '%s\n' 'box "Block"' | cmp - "$2" +fi +printf '%s' '' +"#, + )?; + fs::set_permissions(root.join("pikchr"), fs::Permissions::from_mode(0o700))?; + let args = [ + "convert", + "--extension", + "diagram", + "--pikchr", + "./pikchr", + "--fail-on-warnings", + "doc.adoc", + ]; + let run = run_acdc_in(root, &args, None)?; + assert!(run.status.success(), "{}", output_text(&run.stderr)); + let html = fs::read_to_string(root.join("doc.html"))?; + assert!(html.contains("Figure 1. External")); + for (name, alt) in [("diagram", "diagram"), ("flow", "Flow")] { + assert!(root.join(format!("images/{name}.svg")).is_file()); + assert!(html.contains(&format!( + r#"src="images/{name}.svg" alt="{alt}" width="42" height="18""# + ))); + } + let mut secure = args.to_vec(); + secure.extend(["--safe-mode", "secure"]); + let denied = run_acdc_in(root, &secure, None)?; + assert!(!denied.status.success()); + assert!(output_text(&denied.stderr).contains("pikchr requires unsafe mode")); + for (source, message) in [ + ( + "pikchr::charts/flow.pikchr[png]", + "unsupported pikchr format", + ), + ( + ":pikchr: other\n\n[pikchr]\n----\nbox\n----", + "set the pikchr executable", + ), + ( + "pikchr::charts/flow.pikchr[pikchr=other]", + "set the pikchr executable", + ), + ] { + fs::write(root.join("doc.adoc"), source)?; + let run = run_acdc_in(root, &args, None)?; + assert!(!run.status.success()); + assert!(output_text(&run.stderr).contains(message)); + } + Ok(()) + } + + #[test] + fn pikchr_reports_plain_and_html_errors_and_preserves_previous_image() -> TestResult { + let dir = tempfile::tempdir()?; + let root = dir.path(); + fs::write( + root.join("doc.adoc"), + "[pikchr,example]\n----\nbox with ???\n----", + )?; + fs::write(root.join("example.svg"), "previous image")?; + for (command, message) in [ + ( + "printf '%05000d\\nERROR: unrecognized token\\n' 0; exit 1", + "ERROR: unrecognized token", + ), + ( + "printf '%s' '
ERROR: expected & here
'", + "ERROR: expected & here", + ), + ] { + fs::write(root.join("pikchr"), format!("#!/bin/sh\n{command}\n"))?; + fs::set_permissions(root.join("pikchr"), fs::Permissions::from_mode(0o700))?; + let run = run_acdc_in( + root, + &[ + "convert", + "--extension", + "diagram", + "--pikchr", + "./pikchr", + "--fail-on-warnings", + "doc.adoc", + ], + None, + )?; + assert!(!run.status.success()); + assert!( + output_text(&run.stderr).contains(message), + "{}", + output_text(&run.stderr) + ); + assert!(fs::read_to_string(root.join("doc.html"))?.contains("box with ???")); + assert_eq!( + fs::read_to_string(root.join("example.svg"))?, + "previous image" + ); + } + Ok(()) + } + + #[test] + fn dpic_wraps_source_once_and_publishes_svg_from_stdout() -> TestResult { + let dir = tempfile::tempdir()?; + let root = dir.path(); + fs::create_dir(root.join("charts"))?; + fs::write( + root.join("charts/flow.pic"), + ".PS 2\nbox \"File\"\n.PE # done\n", + )?; + fs::write( + root.join("doc.adoc"), + "= Charts\n:imagesdir: images\n\n[dpic,inline-chart]\n....\nbox \"Block\"\n....\n\n.External\ndpic::charts/flow.pic[svg,alt=Flow]", + )?; + fs::write( + root.join("dpic"), + r#"#!/bin/sh +set -eu +test "$#" = 3 +test "$1" = -v +test "$2" = -z +if test -f flow.pic; then + cmp "$3" flow.pic +else + printf '%s\n' '.PS' 'box "Block"' '.PE' | cmp - "$3" +fi +printf '%s' '' +"#, + )?; + fs::set_permissions(root.join("dpic"), fs::Permissions::from_mode(0o700))?; + let args = [ + "convert", + "--extension", + "diagram", + "--dpic", + "./dpic", + "--fail-on-warnings", + "doc.adoc", + ]; + let run = run_acdc_in(root, &args, None)?; + assert!(run.status.success(), "{}", output_text(&run.stderr)); + let html = fs::read_to_string(root.join("doc.html"))?; + assert!(html.contains("Figure 1. External")); + for (name, alt) in [("inline-chart", "inline chart"), ("flow", "Flow")] { + assert!(root.join(format!("images/{name}.svg")).is_file()); + assert!(html.contains(&format!( + r#"src="images/{name}.svg" alt="{alt}" width="20" height="10""# + ))); + } + + let mut secure = args.to_vec(); + secure.extend(["--safe-mode", "secure"]); + let denied = run_acdc_in(root, &secure, None)?; + assert!(!denied.status.success()); + assert!(output_text(&denied.stderr).contains("dpic requires unsafe mode")); + + for (source, message) in [ + ("dpic::charts/flow.pic[png]", "unsupported dpic format"), + ( + ":dpic: other\n\n[dpic]\n----\nbox\n----", + "set the dpic executable", + ), + ( + "dpic::charts/flow.pic[dpic=other]", + "set the dpic executable", + ), + ] { + fs::write(root.join("doc.adoc"), source)?; + let run = run_acdc_in(root, &args, None)?; + assert!(!run.status.success()); + assert!(output_text(&run.stderr).contains(message)); + } + Ok(()) + } + + #[test] + fn oversized_dpic_stdout_preserves_the_previous_asset() -> TestResult { + let dir = tempfile::tempdir()?; + let root = dir.path(); + fs::write(root.join("doc.adoc"), "[dpic,figure]\n----\nbox\n----")?; + fs::write(root.join("figure.svg"), "previous image")?; + fs::write( + root.join("dpic"), + "#!/bin/sh\ndd if=/dev/zero bs=1048576 count=17\n", + )?; + fs::set_permissions(root.join("dpic"), fs::Permissions::from_mode(0o700))?; + let run = run_acdc_in( + root, + &[ + "convert", + "--extension", + "diagram", + "--dpic", + "./dpic", + "--fail-on-warnings", + "doc.adoc", + ], + None, + )?; + assert!(!run.status.success()); + assert!(output_text(&run.stderr).contains("16 MiB")); + assert_eq!( + fs::read_to_string(root.join("figure.svg"))?, + "previous image" + ); + Ok(()) + } + + #[test] + fn msc_renders_block_and_local_file_with_the_selected_font() -> TestResult { + let dir = tempfile::tempdir()?; + let root = dir.path(); + fs::create_dir(root.join("charts"))?; + fs::write(root.join("charts/exchange.msc"), "file chart")?; + fs::write( + root.join("mscgen"), + r#"#!/bin/sh +set -eu +test "$#" = 7 +test "$1" = -o && test "$3" = -T && test "$4" = svg && test "$5" = -F && test "$7" = - +case "$(cat)" in + 'file chart') test -f exchange.msc && test "$6" = 'File Font' ;; + 'block chart') test -f doc.adoc && test "$6" = 'Block Font' ;; + *) exit 2 ;; +esac +printf '%s' '' > "$2" +"#, + )?; + fs::set_permissions(root.join("mscgen"), fs::Permissions::from_mode(0o700))?; + fs::write( + root.join("doc.adoc"), + "= Charts\n:msc-font: Block Font\n:msc-format: svg\n:imagesdir: images\n\n[msc,request]\n....\nblock chart\n....\n\n.Reply\nmsc::charts/exchange.msc[svg,font=File Font,alt=Reply]", + )?; + let args = [ + "convert", + "--extension", + "diagram", + "--mscgen", + "./mscgen", + "--fail-on-warnings", + "doc.adoc", + ]; + let run = run_acdc_in(root, &args, None)?; + assert!(run.status.success(), "{}", output_text(&run.stderr)); + let html = fs::read_to_string(root.join("doc.html"))?; + for (name, alt) in [("request", "request"), ("exchange", "Reply")] { + assert!(root.join(format!("images/{name}.svg")).is_file()); + assert!(html.contains(&format!( + r#"src="images/{name}.svg" alt="{alt}" width="16" height="8""# + ))); + } + assert!(html.contains("Figure 1. Reply")); + for (source, expected) in [ + ("msc::charts/exchange.msc[pdf]", "unsupported msc format"), + ( + ":mscgen: other\n\n[msc]\n----\nsource\n----", + "set the mscgen executable", + ), + ( + "msc::charts/exchange.msc[mscgen_js=other]", + "set the mscgen executable", + ), + ] { + fs::write(root.join("doc.adoc"), source)?; + let output = run_acdc_in(root, &args, None)?; + assert!(!output.status.success()); + assert!(output_text(&output.stderr).contains(expected)); + } + Ok(()) + } + + #[test] + fn graphviz_file_macro_preserves_image_semantics_and_reads_relative_to_the_invocation() + -> TestResult { + let dir = tempfile::tempdir()?; + let root = dir.path(); + fs::create_dir_all(root.join("source/parts/graphs"))?; + fs::create_dir(root.join("out"))?; + fs::write( + root.join("source/parts/graphs/chart.dot"), + "digraph { input -> output }", + )?; + fs::write( + root.join("source/parts/part.adoc"), + ".Flow\ngraphviz::graphs/chart.dot[svg,alt=\"*Graph*\"]", + )?; + fs::write( + root.join("source/doc.adoc"), + "= Document\n\n:imagesdir: images\n\ninclude::parts/part.adoc[]\n\ngraphviz::parts/graphs/chart.dot[svg]\n\n.Next\nimage::next.png[]", + )?; + fs::write( + root.join("dot"), + r#"#!/bin/sh +set -eu +test -f chart.dot +test "$(cat)" = 'digraph { input -> output }' +test "$1" = -o +test "$3" = -Tsvg +printf '%s' '' > "$2" +"#, + )?; + fs::set_permissions(root.join("dot"), fs::Permissions::from_mode(0o700))?; + let args = [ + "convert", + "--extension", + "diagram", + "--graphviz-dot", + "./dot", + "--fail-on-warnings", + "source/doc.adoc", + "-o", + "out/doc.html", + ]; + let run = run_acdc_in(root, &args, None)?; + assert!(run.status.success(), "{}", output_text(&run.stderr)); + let html = fs::read_to_string(root.join("out/doc.html"))?; + assert!( + html.contains(r#"src="images/chart.svg" alt="*Graph*" width="10" height="20""#), + "{html}" + ); + assert!(html.contains(r#"src="images/chart.svg" alt="Diagram""#)); + assert!(html.contains("Figure 1. Flow") && html.contains("Figure 2. Next")); + assert!(root.join("out/images/chart.svg").is_file()); + + fs::write(root.join("source/doc.adoc"), "graphviz::missing.dot[svg]")?; + let mut safe_args = args.to_vec(); + safe_args.extend(["--safe-mode", "secure"]); + let denied = run_acdc_in(root, &safe_args, None)?; + assert!(!denied.status.success()); + assert!(output_text(&denied.stderr).contains("Graphviz requires unsafe mode")); + let run = run_acdc_in(root, &args, None)?; + assert!(!run.status.success()); + let html = fs::read_to_string(root.join("out/doc.html"))?; + assert!( + html.contains("Failed to generate image") + && html.contains("graphviz::missing.dot[svg]") + ); + Ok(()) + } + + #[test] + fn graphviz_file_macro_preserves_its_input_on_an_output_collision() -> TestResult { + let dir = tempfile::tempdir()?; + let root = dir.path(); + setup(root)?; + fs::write(root.join("chart.svg"), "digraph { keep }")?; + fs::write(root.join("doc.adoc"), "graphviz::chart.svg[svg]")?; + let result = run_acdc_in( + root, + &[ + "convert", + "--extension", + "diagram", + "--graphviz-dot", + "./renderer", + "--fail-on-warnings", + "doc.adoc", + ], + None, + )?; + assert!(!result.status.success()); + assert!(output_text(&result.stderr).contains("overwrite its source file")); + assert_eq!( + fs::read_to_string(root.join("chart.svg"))?, + "digraph { keep }" + ); + Ok(()) + } + + #[test] + fn graphviz_uses_the_configured_dot_and_source_position_layout() -> TestResult { + let dir = tempfile::tempdir()?; + let root = dir.path(); + fs::create_dir(root.join("source"))?; + fs::create_dir(root.join("out"))?; + fs::write( + root.join("dot"), + r#"#!/bin/sh +set -eu +test -f graph.adoc +test "$1" = -o +test "$3" = -Tsvg +test "$(cat)" = 'digraph { start -> finish }' +printf '%s\n' "$4" >> layouts +cat > "$2" <<'SVG' + + + +SVG +"#, + )?; + fs::set_permissions(root.join("dot"), fs::Permissions::from_mode(0o700))?; + let body = "digraph { start -> finish }"; + fs::write( + root.join("source/graph.adoc"), + format!( + "= Flow\n:graphviz-format: svg\n:graphviz-layout: dot\n\n[graphviz]\n----\n{body}\n----\n\n[graphviz,layout=neato]\n....\n{body}\n...." + ), + )?; + let args = [ + "convert", + "--extension", + "diagram", + "--graphviz-dot", + "./dot", + "--fail-on-warnings", + "source/graph.adoc", + "-o", + "out/graph.html", + ]; + let output = run_acdc_in(root, &args, None)?; + assert!(output.status.success(), "{}", output_text(&output.stderr)); + assert_eq!( + fs::read_to_string(root.join("source/layouts"))?, + "-Kdot\n-Kneato\n" + ); + let html = fs::read_to_string(root.join("out/graph.html"))?; + let mut diagrams = 0; + for entry in fs::read_dir(root.join("out"))? { + let entry = entry?; + let path = entry.path(); + if path.extension().is_some_and(|ext| ext == "svg") { + let name = entry.file_name(); + assert!(html.contains(&format!("src=\"{}\"", name.to_string_lossy()))); + diagrams += 1; + } + } + assert_eq!(diagrams, 2); + assert_eq!(html.matches(r#"width="106" height="26""#).count(), 2); + + fs::write( + root.join("source/graph.adoc"), + format!("[graphviz,graphvizdot=other]\n....\n{body}\n...."), + )?; + let denied = run_acdc_in(root, &args, None)?; + assert!(!denied.status.success()); + assert!(output_text(&denied.stderr).contains("set the Graphviz executable")); + assert_eq!( + fs::read_to_string(root.join("source/layouts"))?, + "-Kdot\n-Kneato\n" + ); + Ok(()) + } + + #[test] + fn renderer_scratch_is_private_with_a_permissive_umask() -> TestResult { + let dir = tempfile::tempdir()?; + let root = dir.path(); + setup(root)?; + fs::write(root.join("source.adoc"), SOURCE)?; + fs::write( + root.join("renderer"), + r#"#!/bin/sh +set -eu +pwd > ../scratch-path +ls -ld . > ../scratch-mode +printf '%s' '' > "$4" +"#, + )?; + let output = std::process::Command::new("sh") + .args([ + "-c", + r#"umask 000; exec "$@""#, + "sh", + env!("CARGO_BIN_EXE_acdc"), + "convert", + "--extension", + "diagram", + "--wavedrom-cli", + "./renderer", + "--fail-on-warnings", + "source.adoc", + ]) + .current_dir(root) + .output()?; + assert!(output.status.success(), "{}", output_text(&output.stderr)); + let mode = fs::read_to_string(root.join("images/scratch-mode"))?; + // The parent filesystem may propagate setgid without granting group access. + assert!( + mode.starts_with("drwx------") || mode.starts_with("drwx--S---"), + "{mode}" + ); + let scratch = fs::read_to_string(root.join("images/scratch-path"))?; + assert!(!Path::new(scratch.trim_end()).exists()); + assert!(root.join("images/clock.svg").is_file()); + Ok(()) + } + + #[test] + fn svg_type_follows_block_options_and_scoped_document_defaults() -> TestResult { + use std::fmt::Write as _; + + let blocks = [ + ("", "shared,svg,opts=other"), + (":wavedrom-svg-type: interactive", "renderer,svg"), + ("", "local,svg,svg-type=static"), + ("", "explicit,svg,svg-type=unknown,opts=inline"), + (":wavedrom-svg-type!:", "inherited,svg"), + ("", "object,svg,opts=interactive"), + ("", r#"both,svg,opts="interactive,inline""#), + (":diagram-svg-type!:", "plain,svg"), + ]; + let mut doc = String::from("= Guide\n:diagram-svg-type: inline\n"); + for (attrs, block) in blocks { + writeln!(doc, "\n{attrs}\n\n[wavedrom,{block}]\n....\nclock\n....")?; + } + for mode in ["asciidoctor", "draft"] { + let dir = tempfile::tempdir()?; + let root = dir.path(); + setup(root)?; + fs::create_dir(root.join("source"))?; + fs::create_dir(root.join("out"))?; + fs::write(root.join("source/doc.adoc"), &doc)?; + let result = convert( + root, + &[ + "--embedded", + "--compatibility-mode", + mode, + "source/doc.adoc", + "-o", + "out/doc.html", + ], + None, + )?; + assert!(result.status.success(), "{}", output_text(&result.stderr)); + let html = fs::read_to_string(root.join("out/doc.html"))?; + assert_eq!(html.matches(" TestResult { + let dir = tempfile::tempdir()?; + setup(dir.path())?; + fs::write(dir.path().join("renderer"), "#!/bin/sh\ncp \"$2\" \"$4\"\n")?; + let pixels = r#"width="240px" height="30" viewBox="0 0 1 1""#; + let cases = [ + (",svg", pixels, r#"alt="Diagram" width="240" height="30">"#), + ( + "clock,svg,width=50%,scale=0.5", + pixels, + r#"alt="clock" width="50%" height="15">"#, + ), + ( + "reset,svg,height=7", + pixels, + r#"alt="reset" width="240" height="7">"#, + ), + ( + "both,svg,width=12,height=23", + pixels, + r#"alt="both" width="12" height="23">"#, + ), + ( + "points,svg", + r#"width="383.212pt" height="250.908pt""#, + r#"alt="points" width="509" height="333">"#, + ), + ( + "box,svg", + r#"width="100%" viewBox="4 6 80 24""#, + r#"alt="box" width="80" height="24">"#, + ), + ("unknown,svg", r#"width="100%""#, r#"alt="unknown">"#), + ]; + let source = cases.map(|(attributes, geometry, _)| { + format!("[wavedrom,{attributes}]\n....\n\n....") + }).join("\n\n"); + let output = convert(dir.path(), &["--stdin", "--embedded"], Some(&source))?; + assert!(output.status.success(), "{}", output_text(&output.stderr)); + let html = output_text(&output.stdout); + for (_, _, expected) in cases { + assert!(html.contains(expected), "missing {expected} in {html}"); + } + Ok(()) + } + + #[test] + fn titled_diagram_listing_shares_the_figure_counter_with_authored_images() -> TestResult { + let dir = tempfile::tempdir()?; + setup(dir.path())?; + let source = ".Timing\n[wavedrom,clock,svg]\n----\nwave body\n----\n\n.Photo\nimage::photo.png[]\n\n----\nordinary listing\n----"; + let output = convert(dir.path(), &["--stdin", "--embedded"], Some(source))?; + assert!(output.status.success(), "{}", output_text(&output.stderr)); + let html = output_text(&output.stdout); + assert!(html.contains("src=\"clock.svg\"")); + assert!(html.contains("Figure 1. Timing") && html.contains("Figure 2. Photo")); + assert!(html.contains("
ordinary listing
")); + assert!(dir.path().join("clock.svg").is_file()); + Ok(()) + } + + #[test] + fn nested_diagrams_preserve_references_captions_and_cell_local_output() -> TestResult { + let source = include_str!("fixtures/nested-diagrams.adoc"); + for mode in ["asciidoctor", "draft"] { + let dir = tempfile::tempdir()?; + setup(dir.path())?; + let output = convert( + dir.path(), + &["--stdin", "--embedded", "--compatibility-mode", mode], + Some(source), + )?; + assert!( + output.status.success(), + "{mode}: {}", + output_text(&output.stderr) + ); + + let html = output_text(&output.stdout); + let mut remaining = html.as_str(); + for fragment in [ + r##"href="#clock">Clock trace"##, + r#"class="sidebarblock""#, + "
  • ", + r#"id="clock" class="imageblock timing""#, + r#"src="public/clock.svg""#, + "Figure 1. Clock trace", + "
  • ", + "", + "
    ", + r#"src="public/after.svg""#, + "Figure 2. Output trace", + ] { + (_, remaining) = remaining + .split_once(fragment) + .ok_or_else(|| format!("{mode}: missing or misplaced {fragment}"))?; + } + for asset in [ + "public/clock.svg", + "staging/reset.svg", + "public/enable.svg", + "public/after.svg", + ] { + assert!(dir.path().join(asset).is_file(), "{mode}: missing {asset}"); + } + assert!(!dir.path().join("public/reset.svg").exists()); + } + Ok(()) + } + + #[test] + fn failed_diagram_in_an_include_keeps_source_and_reports_a_warning() -> TestResult { + let dir = tempfile::tempdir()?; + let root = dir.path(); + setup(root)?; + fs::write(root.join("renderer"), "#!/bin/sh\nexit 1\n")?; + fs::write(root.join("clock.svg"), "previous asset")?; + fs::write( + root.join("guide.adoc"), + ":label: clock\n\ninclude::part.adoc[]\n\nAfter.", + )?; + fs::write( + root.join("part.adoc"), + "\n[wavedrom,clock,svg,subs=attributes]\n....\n<{label}> *raw*\n....", + )?; + for strict in [false, true] { + let mut args = vec![ + "convert", + "--extension", + "diagram", + "--wavedrom-cli", + "./renderer", + "--embedded", + "-o", + "-", + "guide.adoc", + ]; + if strict { + args.push("--fail-on-warnings"); + } + let output = run_acdc_in(root, &args, None)?; + let html = output_text(&output.stdout); + let stderr = output_text(&output.stderr); + assert_eq!(output.status.code(), Some(i32::from(strict)), "{stderr}"); + assert!( + stderr.contains("renderer exited") && stderr.contains("part.adoc"), + "{stderr}" + ); + assert!( + html.contains("Failed to generate image:") && html.contains("<clock> *raw*"), + "{html}" + ); + assert!( + html.contains("

    After.

    ") && !html.contains("src=\"clock.svg\""), + "{html}" + ); + } + assert_eq!( + fs::read_to_string(root.join("clock.svg"))?, + "previous asset" + ); + Ok(()) + } + + #[test] + fn diagram_assets_follow_files_streams_and_batches() -> TestResult { + let dir = tempfile::tempdir()?; + let root = dir.path(); + setup(root)?; + for folder in ["first", "second", "output"] { + fs::create_dir(root.join(folder))?; + } + for folder in ["first", "second"] { + fs::write(root.join(folder).join("doc.adoc"), SOURCE)?; + } + let batch = convert(root, &["first/doc.adoc", "second/doc.adoc"], None)?; + assert!(batch.status.success(), "{}", output_text(&batch.stderr)); + for folder in ["first", "second"] { + let path = root.join(folder); + assert!( + fs::read_to_string(path.join("doc.html"))?.contains("src=\"images/clock.svg\"") + ); + assert!(path.join("images/clock.svg").is_file()); + } + let file = convert(root, &["first/doc.adoc", "-o", "output/custom.html"], None)?; + assert!(file.status.success(), "{}", output_text(&file.stderr)); + assert!(root.join("output/images/clock.svg").is_file()); + + let stream = convert(root, &["--stdin", "-o", "-"], Some(SOURCE))?; + assert!(stream.status.success(), "{}", output_text(&stream.stderr)); + assert!(output_text(&stream.stdout).contains("src=\"images/clock.svg\"")); + assert!(root.join("images/clock.svg").is_file()); + Ok(()) + } + + #[test] + fn diagram_embedded_html_resolves_from_the_source_directory() -> TestResult { + let dir = tempfile::tempdir()?; + let root = dir.path(); + setup(root)?; + fs::create_dir(root.join("source"))?; + fs::write(root.join("source/doc.adoc"), SOURCE)?; + let file = convert( + root, + &["source/doc.adoc", "-a", "data-uri", "-o", "doc.html"], + None, + )?; + assert!(file.status.success(), "{}", output_text(&file.stderr)); + assert!( + fs::read_to_string(root.join("doc.html"))?.contains("data:image/svg+xml;base64,PHN2Zy") + ); + assert!(root.join("source/images/clock.svg").is_file()); + Ok(()) + } + + #[test] + fn imagesoutdir_stages_diagrams_and_preserves_published_links() -> TestResult { + let dir = tempfile::tempdir()?; + let root = dir.path().join("build #1%"); + fs::create_dir(&root)?; + setup(&root)?; + for folder in ["source", "out"] { + fs::create_dir(root.join(folder))?; + } + let source = "= Guide\n:imagesdir: public\n:imagesoutdir: staging\n\n[wavedrom,boards/clock,svg]\n....\nfirst\n....\n\n:imagesoutdir!:\n\n[wavedrom,other,svg]\n....\nsecond\n....\n"; + fs::write(root.join("source/doc.adoc"), source)?; + let args = ["source/doc.adoc", "-o", "out/doc.html"]; + let linked = convert(&root, &args, None)?; + assert!(linked.status.success(), "{}", output_text(&linked.stderr)); + let html = fs::read_to_string(root.join("out/doc.html"))?; + assert!(html.contains("src=\"public/boards/clock.svg\"")); + assert!(html.contains("src=\"public/other.svg\"")); + assert!(root.join("staging/boards/clock.svg").is_file()); + assert!(root.join("out/public/other.svg").is_file()); + assert!(!root.join("out/public/boards").exists()); + + let mut embedded_args = args.to_vec(); + embedded_args.extend(["-a", "data-uri"]); + let embedded = convert(&root, &embedded_args, None)?; + assert!( + embedded.status.success(), + "{}", + output_text(&embedded.stderr) + ); + let html = fs::read_to_string(root.join("out/doc.html"))?; + assert_eq!(html.matches("src=\"data:image/svg+xml;base64,").count(), 2); + assert!(root.join("source/public/other.svg").is_file()); + assert!(!root.join("source/public/boards").exists()); + + fs::write( + root.join("source/doc.adoc"), + source.replace("boards/clock,svg]", "boards/clock,svg,opts=inline]"), + )?; + let inline = convert(&root, &args, None)?; + assert!(inline.status.success(), "{}", output_text(&inline.stderr)); + let html = fs::read_to_string(root.join("out/doc.html"))?; + assert!(html.contains(" TestResult { + let dir = tempfile::tempdir()?; + let root = dir.path(); + fs::create_dir(root.join("source"))?; + fs::write( + root.join("source/doc.adoc"), + "[tikz,figure]\n....\npicture\n....\n", + )?; + fs::write( + root.join("engine"), + "#!/bin/sh\nprintf '%%PDF-1.4\\n%%%%EOF\\n' > input.pdf\n", + )?; + fs::write( + root.join("pdf2svg"), + r#"#!/bin/sh +printf '%s' '' > "$2" +"#, + )?; + for tool in ["engine", "pdf2svg"] { + fs::set_permissions(root.join(tool), fs::Permissions::from_mode(0o700))?; + } + let args = [ + "convert", + "--backend", + "pdf", + "--extension", + "diagram", + "--lualatex", + "./engine", + "--fail-on-warnings", + "-o", + "report.pdf", + "source/doc.adoc", + ]; + let missing = run_acdc_in(root, &args, None)?; + assert!(!missing.status.success()); + assert!(output_text(&missing.stderr).contains("requires a configured pdf2svg")); + let mut configured = args.to_vec(); + configured.extend(["--pdf2svg", "./pdf2svg"]); + let file = run_acdc_in(root, &configured, None)?; + assert!(file.status.success(), "{}", output_text(&file.stderr)); + assert!(root.join("source/figure.svg").is_file()); + assert!(fs::read(root.join("report.pdf"))?.starts_with(b"%PDF-")); + configured.extend(["-a", "imagesdir=public", "-a", "imagesoutdir=staged files"]); + let staged = run_acdc_in(root, &configured, None)?; + assert!(staged.status.success(), "{}", output_text(&staged.stderr)); + assert!(root.join("staged files/figure.svg").is_file()); + assert!(!root.join("source/public").exists()); + Ok(()) + } + + #[test] + fn diagram_blocks_reject_every_restricted_safe_mode_before_launch() -> TestResult { + let dir = tempfile::tempdir()?; + setup(dir.path())?; + for mode in ["safe", "server", "secure"] { + let output = convert(dir.path(), &["--safe-mode", mode, "--stdin"], Some(SOURCE))?; + assert!(!output.status.success()); + assert!( + output_text(&output.stderr).contains("requires unsafe mode"), + "{}", + output_text(&output.stderr) + ); + assert!(!dir.path().join("images").exists()); + } + Ok(()) + } +} diff --git a/acdc-cli/tests/convert/fixtures/nested-diagrams.adoc b/acdc-cli/tests/convert/fixtures/nested-diagrams.adoc new file mode 100644 index 000000000..481ae98ce --- /dev/null +++ b/acdc-cli/tests/convert/fixtures/nested-diagrams.adoc @@ -0,0 +1,40 @@ += Timing diagrams +:imagesdir: public + +See <>. + +**** +* Measure the clock ++ +[#clock.timing] +.Clock trace +[wavedrom,clock,svg] +---- +{signal: [{name: 'clock', wave: 'p...'}]} +---- +**** + +[cols="a,a"] +|=== +|Reset trace. + +:imagesoutdir: staging + +[wavedrom,reset,svg] +.... +{signal: [{name: 'reset', wave: '01..'}]} +.... + +|Enable trace. + +[wavedrom,enable,svg] +.... +{signal: [{name: 'enable', wave: '0.1.'}]} +.... +|=== + +.Output trace +[wavedrom,after,svg] +.... +{signal: [{name: 'after', wave: '01..'}]} +.... diff --git a/converters/terminal/CHANGELOG.md b/converters/terminal/CHANGELOG.md index 4420b13ac..51c3d56f0 100644 --- a/converters/terminal/CHANGELOG.md +++ b/converters/terminal/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- The terminal image protocol can open absolute image paths containing spaces. + - Applications can register this converter using its built-in backend names and variant choices. - Selected text postprocessors can transform the completed terminal output for each document, including documents sent to a pager. diff --git a/converters/terminal/src/image.rs b/converters/terminal/src/image.rs index a9411b3b1..e2a43f77f 100644 --- a/converters/terminal/src/image.rs +++ b/converters/terminal/src/image.rs @@ -29,12 +29,16 @@ impl<'a, W: Write> TerminalVisitor<'a, '_, W> { #[cfg(feature = "images")] let rendered_protocol_image = if let SourceKind::Path(path) = image.source().kind() { let config = image_config(image, self.converter.terminal_width); - let path = resolve_target(&path.to_string_lossy(), traversal); + let path = if path.is_absolute() { + std::borrow::Cow::Borrowed(path) + } else { + std::borrow::Cow::Owned(resolve_target(&path.to_string_lossy(), traversal).into()) + }; self.writer_mut().flush()?; let displayed = viuer::print_from_file(&path, &config).is_ok(); if !displayed { self.diagnostics.warn_with_advice( - format!("failed to display image `{path}`"), + format!("failed to display image `{}`", path.display()), "Verify the image path is relative to the input document and that the terminal image feature can load it.", ); } diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md new file mode 100644 index 000000000..c219445af --- /dev/null +++ b/extensions/diagram/CHANGELOG.md @@ -0,0 +1,114 @@ +# Changelog + +## [Unreleased] + +- Honor renderer option defaults, `literal` and `jpg` format aliases, and explicit image dimensions on diagram file macros. + +- Caption local images with `meme::photo.jpg[Top,Bottom]` and `--extension diagram --magick PATH`. PNG is the default. Use `format=gif` for GIF and `opts=noupcase` to preserve letter case. + +- Render `[vegalite]` blocks and `vegalite::chart.json[]` files with `--vl2vg PATH`. Supply the Vega SVG renderer with `--vg2svg PATH`. The compiler feeds its Vega specification to the selected SVG or PNG renderer. + +- Render `[vega]` blocks and `vega::chart.json[]` files with `--vg2svg PATH`. SVG uses `--vg2svg`. Supply `--vg2png PATH` for PNG and `--vl2vg PATH` for Vega-Lite specifications. + +- Render `[salt]` blocks and `salt::chart.salt[]` files with `--plantuml PATH`. Supply the PlantUML executable to render Salt wireframes as PNG, SVG, or text. + +- Render `[plantuml]` blocks and `plantuml::chart.puml[]` files with `--plantuml PATH`. Choose PNG, SVG, ASCII `atxt`, or Unicode `txt` and `utxt`. Local includes resolve from the diagram directory. Configure Graphviz with `--graphviz-dot` or use the built-in Smetana layout. + +- Render `[penrose]` blocks and `penrose::chart.substance[]` files with `--roger PATH`. Provide `domain_file` and `style_file` relative to the diagram source. Use `variation` to choose a layout. + +- Render `[erd]` blocks and `erd::chart.erd[]` files with `--erd PATH`. Configure Graphviz with `--graphviz-dot PATH`. The ERD renderer produces DOT and Graphviz writes the final PNG or SVG. + +- Render `[lilypond]` blocks and `lilypond::chart.ly[]` files with `--lilypond PATH`. The output is a cropped PNG or PDF score. Set `resolution` to select the raster resolution. + +- Render `[oxdraw]` blocks and `oxdraw::chart.mmd[]` files with `--oxdraw PATH`. SVG is the default. Use `background` and `scale` to change the output. + +- Render `[mermaid]` blocks and `mermaid::chart.mmd[]` files with `--mmdc PATH`. Choose PNG or SVG and set `theme`, `scale`, or a local `config` file. For SVGs with a nonzero viewBox origin, acdc uses the declared width and height. Asciidoctor Diagram 3.2.1 subtracts the origin from those dimensions. + +- Render `[bpmn]` blocks and `bpmn::chart.bpmn[]` files with `--bpmn-js PATH`. Choose PNG (default), SVG, PDF, or JPEG. Set `width` and `height` to select the canvas size. + +- Render `[umlet]` blocks and `umlet::chart.uxf[]` files with `--umlet PATH`. Choose SVG (default), PNG, PDF, or GIF using a UMLet command-line launcher. Supports the SVG 1.0 declaration emitted by the standalone UMLet distribution. + +- Render `[gnuplot]` blocks and `gnuplot::chart.gp[]` files with `--gnuplot PATH`. Choose PNG, SVG, GIF, or a literal text plot. Set `width` and `height` together to select a terminal size. + +- Render `[tape]` blocks and `tape::chart.tape[]` files with `--vhs PATH`. GIF is the default. Use `format=svg` for an SVG recording. Tape scripts run in unsafe mode. + +- Render `[ditaa]` blocks and `ditaa::chart.ditaa[]` files with `--ditaa PATH`. Choose PNG (default), SVG, or literal text. Set `round-corners=true`, `shadows=false`, or `scale` to change the drawing. + +- Render `[diagrams]` blocks and `diagrams::chart.py[]` files with `--diagrams-python PATH`. Render Python diagrams as PNG (default), SVG, or PDF with an interpreter that has the diagrams package installed. + +- Render `[syntrax]` blocks and `syntrax::chart.spec[]` files with `--syntrax PATH`. Choose PNG or SVG. Use `heading`, `scale`, `style-file`, and `transparent=true` to customize a railroad diagram. + +- Render `[svgbob]` blocks and `svgbob::chart.bob[]` files with `--svgbob PATH`. Choose SVG or literal text. The SVG renderer accepts `font-family`, `font-size`, `stroke-width`, and `scale`. + +- Render `[a2s]` blocks and `a2s::chart.txt[]` files with `--a2s PATH`. SVG is the default. Use `format=txt` for the original text, `scalex` and `scaley` for dimensions, or `noblur=true` for crisp edges. + +- Render `[pintora]` blocks and `pintora::chart.pintora[]` files with `--pintora PATH`. Choose PNG (default) or SVG. Set `theme`, `width`, `background-color`, or `pixel-ratio` to customize the result. + +- Render `[symbolator]` blocks and `symbolator::chart.vhd[]` files with `--symbolator PATH`. Choose PNG (default), PDF, or SVG. + +- Render `[shaape]` blocks and `shaape::chart.shaape[]` files with `--shaape PATH`. PNG is the default. Select SVG with `format=svg`. + +- Render `[d2]` blocks and `d2::chart.d2[]` files with `--d2 PATH`. SVG is the default. PNG and PDF require the corresponding D2 browser support. Set `theme`, `layout`, or `sketch` to change the drawing. + +- Render `[graphviz_py]` blocks and `graphviz_py::chart.dot[]` files with `--graphviz-py PATH`. Choose PNG (default), PDF, or SVG. Set `layout` and `argument` to pass a layout engine and a preprocessor argument. + +- Render `[dbml]` blocks and `dbml::chart.dbml[]` files with `--dbml-renderer PATH`. Output is SVG. + +- Render `[smcat]` blocks and `smcat::chart.smcat[]` files with `--smcat PATH`. Set `direction` or `engine` to choose the SVG layout. + +- Render `[nomnoml]` blocks and `nomnoml::chart.nomnoml[]` files with `--nomnoml PATH`. Output is SVG. + +- Render `[rackdiag]` blocks and `rackdiag::chart.diag[]` files with `--rackdiag PATH`. PNG is the default. PDF, SVG, and a custom font file via `fontpath` are also supported. + +- Render `[packetdiag]` blocks and `packetdiag::chart.diag[]` files with `--packetdiag PATH`. PNG is the default. PDF, SVG, and a custom font file via `fontpath` are also supported. + +- Render `[nwdiag]` blocks and `nwdiag::chart.diag[]` files with `--nwdiag PATH`. PNG is the default. PDF, SVG, and a custom font file via `fontpath` are also supported. + +- Render `[actdiag]` blocks and `actdiag::chart.diag[]` files with `--actdiag PATH`. PNG is the default. PDF, SVG, and a custom font file via `fontpath` are also supported. + +- Render `[seqdiag]` blocks and `seqdiag::chart.diag[]` files with `--seqdiag PATH`. PNG is the default. PDF, SVG, and a custom font file via `fontpath` are also supported. + +- Render `[blockdiag]` blocks and `blockdiag::chart.diag[]` files with `--blockdiag PATH`. PNG is the default. PDF, SVG, and a custom font file via `fontpath` are also supported. + +- Render packet and binary layouts as SVG from `[bytefield]` blocks or `bytefield::layout.edn[]` file macros with `--extension diagram --bytefield-svg PATH`. + +- Render GoAT ASCII diagrams from `[goat]` blocks and `goat::chart.txt[]` file macros as SVG with `--extension diagram --goat PATH`. Set `svg-color-dark-scheme` and `svg-color-light-scheme` to choose the colors. + +- Render Pikchr source from `[pikchr]` blocks and `pikchr::chart.pikchr[]` file macros as SVG with `--extension diagram --pikchr PATH`. Syntax errors report the renderer’s diagnostic and preserve the previous image. + +- Render PIC source from `[dpic]` blocks or `dpic::chart.pic[]` file macros as SVG with `--extension diagram --dpic PATH`. acdc accepts both bare source and pictures already enclosed in `.PS` and `.PE`. Asciidoctor Diagram 3.2.1 can append a duplicate closing delimiter to a complete picture. + +- Render message sequence charts from `[msc]` blocks or `msc::chart.msc[svg]` with `--extension diagram --mscgen PATH`. PNG is the default. Use `font=` or `msc-font` to select a PNG font. + +- Render a local DOT file with `graphviz::chart.dot[svg,alt="*Graph*"]`. File macros use the configured Graphviz executable and share the document’s include byte limit. + +- Render Graphviz listing and literal blocks with the registered `dot` executable (`--extension diagram --graphviz-dot PATH` in the CLI). PNG is the default. SVG, PDF, and the `layout` setting are supported. + +- On Unix, only the current user can access the temporary directory containing a diagram’s source and intermediate files, even when the output directory is shared. + +- Use `diagram-svg-type=inline` to embed SVG markup or `interactive` to render an HTML object. The default `static` links an image. WaveDrom and TikZ each accept a renderer-specific setting and a per-block override. + +- HTML output uses the generated image’s width and height for WaveDrom SVG and PNG diagrams and for TikZ SVG diagrams. A numeric `scale` multiplies those defaults, and an explicit `width` or `height` overrides that dimension. acdc uses CSS pixel conversions for inches, centimeters, millimeters, and picas, and takes `viewBox` extents independently of their origin. These cases can differ from Asciidoctor Diagram. + +- Set `imagesoutdir` to stage WaveDrom and TikZ files in a local relative directory. Linked images use `imagesdir`, and embedded images read the staged files. acdc rejects absolute directories and parent traversal. + +- WaveDrom and TikZ can write named diagrams into subdirectories of `imagesdir`. For example, `[wavedrom,boards/clock,svg]` produces and links to `boards/clock.svg`. + +- WaveDrom and TikZ images use the authored `alt`, including `alt=""` for decorative diagrams. The default label comes from the target name, or `Diagram` for unnamed images. + +- Failed WaveDrom and TikZ diagrams now produce a located warning and show the error and source in a listing. As in Asciidoctor Diagram, `diagram-on-error` defaults to `log`. Set it to `abort` to stop parsing. + +- WaveDrom and TikZ blocks accept `subs=attributes` to expand document attributes before rendering. With the default settings, braces and backslashes pass through verbatim. Unnamed images use the expanded source for their filenames. Only the attribute step of a substitution group is applied to diagram source. + +- WaveDrom and TikZ also render listing blocks delimited by `----`. They accept the same source, attributes, and output formats as literal blocks delimited by `....`. + +- Set `diagram-format` to choose a document-wide output format for WaveDrom and TikZ. A renderer-specific format or an explicit block format takes precedence. + +- Applications can supply separate directories for linked and embedded HTML diagrams + when the converted file lives outside the source directory. Passing a single + directory still places all generated assets there. TikZ defaults to SVG for + the PDF backend, which requires a configured pdf2svg executable to embed the diagram. + +- Applications can register the `tikz` literal-block style to produce PDF or SVG with a caller-selected LuaLaTeX executable. Use `preamble=true` and a `~~~~` line for package and font declarations. Rendering requires unsafe mode and runs with shell escape disabled. + +- Applications can generate SVG or PNG images from `[wavedrom, ,svg]` or `[wavedrom, ,png]` literal blocks by registering the WaveDrom style with a trusted executable and output directory. The generated image respects the block’s `imagesdir`. Rendering requires unsafe mode. diff --git a/extensions/diagram/Cargo.toml b/extensions/diagram/Cargo.toml new file mode 100644 index 000000000..96123e30d --- /dev/null +++ b/extensions/diagram/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "acdc-diagram" +version = "0.1.0" +edition.workspace = true +license.workspace = true +description = "Native diagram extensions for acdc" +readme = "README.adoc" +publish = false + +[dependencies] +acdc-parser.workspace = true +image.workspace = true +png = "0.18" +roxmltree = "0.21" +base64.workspace = true +sha2.workspace = true +svgtypes = "0.16" +tempfile.workspace = true +url.workspace = true + +[dev-dependencies] +lopdf.workspace = true +acdc-converters-core.workspace = true +acdc-converters-html.workspace = true + +[lints] +workspace = true diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc new file mode 100644 index 000000000..ed655807d --- /dev/null +++ b/extensions/diagram/README.adoc @@ -0,0 +1,307 @@ += Diagram extensions for acdc + +== WaveDrom + +Applications can register the `wavedrom` style for listing blocks (`----`) and literal blocks (`....`). +Supply the path to a trusted `wavedrom-cli` executable and the directory containing the converted document. +The extension runs the executable only for an explicitly registered style in `SafeMode::Unsafe`. +Use this mode for trusted input. The acdc CLI accepts `--extension diagram --wavedrom-cli PATH` when built with the optional `diagram` feature. +For TikZ, supply `--lualatex PATH` and optionally `--pdf2svg PATH`. +The link:../../acdc-cli/README.adoc[CLI guide] describes asset locations for files, streams, and embedded images. + +[source,rust] +---- +let mut builder = acdc_parser::extensions::Registry::builder(); +builder.register_block_style(acdc_diagram::wavedrom(&tool, &output_dir)?)?; +let options = acdc_parser::Options::builder() + .with_safe_mode(acdc_parser::SafeMode::Unsafe) + .build()?; +let parsed = builder.build().parse(source, &options)?.finish()?; +---- + +[source,asciidoc] +---- +[wavedrom, ,svg] +.... +{signal: [{name: 'clock', wave: 'p...'}]} +.... +---- + +Diagram renderers receive the preprocessed body verbatim by default. +Use `subs=attributes` to expand references such as `{signal-label}` with the value in effect at the block. +With expansion enabled, `\{signal-label}` passes a literal `{signal-label}` to the tool. Unknown references stay in the source. +Only the attribute step of a `subs` setting affects diagram source. Formatting, escaping, and callout processing are left to the renderer. + +The first positional argument names the output, e.g. `[wavedrom,clock,svg]` produces `clock.svg`. +Use a relative target such as `boards/rev-a/clock_signal` to write `boards/rev-a/clock_signal.svg` under the current image directory. +Each slash-separated segment accepts ASCII letters, digits, hyphens, and underscores. +Diagram blocks use the final segment as the default alternative text, with hyphens and underscores displayed as spaces. +An unnamed diagram defaults to `Diagram`. Set `alt="Clock and reset"` to supply a label or `alt=""` for a decorative image. +An empty target uses a SHA-256 digest of the renderer input, including the selected layout for Graphviz. Named `target=` and `format=` take precedence. +The image is an ordinary acdc block. Its file is written under the output directory using the `imagesdir` in effect at the block. +Set `:imagesoutdir: staging` to write diagrams under `staging` while keeping `imagesdir` in published links. +Embedding reads the staged file directly. Unset the attribute with `:imagesoutdir!:` to resume writing under `imagesdir`. +The CLI resolves `imagesoutdir` from its working directory. Library callers can set its base with `OutputDirectories::with_imagesoutdir_base`. +Directories used for writing must be relative and cannot contain symlinks, parent traversal, URI escapes, query strings, or fragments. +In HTML, the default `static` SVG type produces an ``. Set `:diagram-svg-type: inline` to embed SVG markup or `:diagram-svg-type: interactive` to use an ``. +A renderer-specific attribute such as `graphviz-svg-type` overrides the shared setting. Each block can override it with `svg-type=static`, `inline`, or `interactive`. +Explicit `opts=inline` or `opts=interactive` takes precedence over `svg-type`. If both options are present, inline wins. +For HTML, SVG diagrams supply default image dimensions from their absolute width and height, or from the `viewBox` when either dimension is unavailable. +PNG diagrams use the pixel width and height of the generated raster. +Use `scale=0.5` to halve those defaults. Explicit `width` and `height` each override the corresponding default. +acdc uses Asciidoctor Diagram’s factor of 1.33 for TeX points and truncates fractional pixels after scaling. +For other physical units acdc uses 96 pixels per inch. A `viewBox` offset does not change its width or height. +Use `[wavedrom,clock,png]` to generate `clock.png`. WaveDrom defaults to SVG. +Set `:diagram-format: svg` to select a common format for the registered renderers. +A block's positional or named format overrides the renderer-specific attribute (such as `graphviz-format`), which in turn overrides `diagram-format`. +Each block uses the document attributes in effect at its location. Unsetting a renderer-specific format restores the shared default. +An empty format reports an unsupported format. Use `:diagram-format!:` to restore automatic selection. +If a renderer fails to generate an image, the default `diagram-on-error=log` reports a warning at the block and continues conversion. +The output contains a listing with the error and the diagram source, including any requested attribute expansion. A previous image file is preserved. +Set `:diagram-on-error: abort` to stop at the first failure. The block's `on-error` attribute overrides the renderer-specific attribute (such as `graphviz-on-error`), which overrides `diagram-on-error` in effect at the block. +Restricted safe modes still stop before running any tool. +Each render uses a temporary directory under the image output directory. On Unix, acdc creates it with owner-only access. On Windows, it inherits the output directory’s access controls. +After success or a renderer error, acdc removes the temporary directory. + +== TikZ + +Register the `tikz` style for listing and literal blocks with the application's LuaLaTeX executable, an optional pdf2svg executable, and the converted document's output directory. + +[source,rust] +---- +builder.register_block_style(acdc_diagram::tikz(&lualatex, Some(&pdf2svg), &output_dir)?)?; +---- + +Use `[tikz,figure,svg,preamble=true,command=lualatex]` on a listing or literal block to produce `figure.svg`. +Put the TeX preamble before a line containing exactly `~~~~`, then the picture after it. +With no separator the complete body becomes picture content. +Use `pdf` for native one-page PDF output. With no explicit format, HTML backends prefer SVG when pdf2svg is configured. The PDF backend defaults to SVG and requires pdf2svg to embed the diagram. Other configurations default to PDF. + +LuaLaTeX runs only in unsafe mode on trusted documents, with shell escape disabled. +The block's `command` and document's `tikz-command` can select only `lualatex`. +Fonts and packages must be discoverable by the caller's TeX installation. +The existing target naming, source-position `imagesdir`, atomic publication, and located error behavior also apply to TikZ. + +== Graphviz + +Register `acdc_diagram::graphviz(&dot, &output_dir)` or pass `--extension diagram --graphviz-dot /usr/bin/dot` in the CLI. +Use `[graphviz,flow,svg]` on a listing or literal block containing DOT source. Graphviz defaults to PNG and also supports PDF. +Set `:graphviz-layout: dot` for subsequent blocks or select an installed layout per block with `layout=neato`. +Graphviz reads the diagram on standard input. Relative resources resolve from the caller's source directory for file conversion. +The CLI also registers `graphviz::graphs/chart.dot[svg,alt="*Graph*"]`. In a library, register `acdc_diagram::graphviz_file(&dot, &output_dir)?` with the registry's `register` method. +The macro reads DOT through the parser's include loader. It accepts UTF-8 and Unicode files with a byte order mark. The target resolves like a local include and its bytes count toward the same document limit. Graphviz resolves resources inside the graph relative to the DOT file. The example writes `chart.svg`. Without an explicit `target` or `alt`, the alternative text is `Diagram`. The file stem follows the same output-name rules as a diagram block. Use `target=other-name` to override it. +Only the caller selects the executable. Rendering requires unsafe mode. + +== Message sequence charts + +Pass `--extension diagram --mscgen /usr/bin/mscgen` to render a listing or literal block styled `[msc]`, or load a local file with `msc::charts/exchange.msc[svg]`. +In a library, register the block style returned by `acdc_diagram::msc` and the block macro returned by `acdc_diagram::msc_file`. +Both forms default to PNG. Select SVG with the positional format, `format=svg`, or `:msc-format: svg`. +Native mscgen uses the `font` argument for PNG output. Set a document default with `:msc-font: DejaVu Sans`. +The macro reads its source through the parser's include loader. Rendering requires unsafe mode and a caller-selected executable. + +== PIC diagrams + +Use `--extension diagram --dpic /usr/bin/dpic` to render PIC source as SVG. Use `[dpic,flow]` on a listing or literal block to write `flow.svg`, or `dpic::charts/flow.pic[]` to read a local picture through the parser's include loader. +In a library, register the block style returned by `acdc_diagram::dpic` and the macro returned by `acdc_diagram::dpic_file`. +acdc adds missing `.PS` and `.PE` delimiters. Existing delimiters, including a size on the opening line, are preserved. +The acdc conversion requires unsafe mode to launch the configured executable. acdc always passes dpic's own `-z` flag, which disables external file access inside PIC source. + +== Pikchr + +Use `--extension diagram --pikchr /usr/bin/pikchr` to render a listing or literal block styled `[pikchr,flow]` as `flow.svg`. Use `pikchr::charts/flow.pikchr[]` to render a local source file. Both forms support SVG. +Library callers register the style returned by `acdc_diagram::pikchr` and the macro returned by `acdc_diagram::pikchr_file`. The caller selects the executable, and rendering requires unsafe mode. +A syntax error produces a located diagnostic. With the default error policy, the listing shows the failed source and the previous image is preserved. + +== GoAT + +Use `--extension diagram --goat /usr/bin/goat` to render ASCII art from a `[goat]` listing or literal block, or from a file with `goat::chart.txt[]`. +Both forms produce SVG. Set `goat-svg-color-dark-scheme` and `goat-svg-color-light-scheme` on the document to select colors. A block or macro can override either with `svg-color-dark-scheme` or `svg-color-light-scheme`. +Library callers register `acdc_diagram::goat` and `acdc_diagram::goat_file` with a trusted executable. Rendering requires unsafe mode. + +== Bytefield + +Use `--extension diagram --bytefield-svg /usr/bin/bytefield-svg` to render packet and binary layouts as SVG. +Place the diagram source in a `[bytefield]` listing or literal block, or load a local file with `bytefield::layout.edn[]`. +Library callers register `acdc_diagram::bytefield` and `acdc_diagram::bytefield_file` with a trusted executable. Rendering requires unsafe mode. + +== blockdiag + +Render `[blockdiag]` blocks and `blockdiag::chart.diag[]` files with `--blockdiag PATH`. PNG is the default. PDF, SVG, and a custom font file via `fontpath` are also supported. Enable the package with `--extension diagram`. + +== seqdiag + +Render `[seqdiag]` blocks and `seqdiag::chart.diag[]` files with `--seqdiag PATH`. PNG is the default. PDF, SVG, and a custom font file via `fontpath` are also supported. Enable the package with `--extension diagram`. + +== actdiag + +Render `[actdiag]` blocks and `actdiag::chart.diag[]` files with `--actdiag PATH`. PNG is the default. PDF, SVG, and a custom font file via `fontpath` are also supported. Enable the package with `--extension diagram`. + +== nwdiag + +Render `[nwdiag]` blocks and `nwdiag::chart.diag[]` files with `--nwdiag PATH`. PNG is the default. PDF, SVG, and a custom font file via `fontpath` are also supported. Enable the package with `--extension diagram`. + +== packetdiag + +Render `[packetdiag]` blocks and `packetdiag::chart.diag[]` files with `--packetdiag PATH`. PNG is the default. PDF, SVG, and a custom font file via `fontpath` are also supported. Enable the package with `--extension diagram`. + +== rackdiag + +Render `[rackdiag]` blocks and `rackdiag::chart.diag[]` files with `--rackdiag PATH`. PNG is the default. PDF, SVG, and a custom font file via `fontpath` are also supported. Enable the package with `--extension diagram`. + +== nomnoml + +Render `[nomnoml]` blocks and `nomnoml::chart.nomnoml[]` files with `--nomnoml PATH`. Output is SVG. Enable the package with `--extension diagram`. + +== smcat + +Render `[smcat]` blocks and `smcat::chart.smcat[]` files with `--smcat PATH`. Set `direction` or `engine` to choose the SVG layout. Enable the package with `--extension diagram`. + +== dbml + +Render `[dbml]` blocks and `dbml::chart.dbml[]` files with `--dbml-renderer PATH`. Output is SVG. Enable the package with `--extension diagram`. + +== graphviz_py + +Render `[graphviz_py]` blocks and `graphviz_py::chart.dot[]` files with `--graphviz-py PATH`. Choose PNG (default), PDF, or SVG. Set `layout` and `argument` to pass a layout engine and a preprocessor argument. Enable the package with `--extension diagram`. + +== d2 + +Render `[d2]` blocks and `d2::chart.d2[]` files with `--d2 PATH`. SVG is the default. PNG and PDF require the corresponding D2 browser support. Set `theme`, `layout`, or `sketch` to change the drawing. Enable the package with `--extension diagram`. + +== shaape + +Render `[shaape]` blocks and `shaape::chart.shaape[]` files with `--shaape PATH`. PNG is the default. Select SVG with `format=svg`. Enable the package with `--extension diagram`. + +== symbolator + +Render `[symbolator]` blocks and `symbolator::chart.vhd[]` files with `--symbolator PATH`. Choose PNG (default), PDF, or SVG. Enable the package with `--extension diagram`. + +== pintora + +Render `[pintora]` blocks and `pintora::chart.pintora[]` files with `--pintora PATH`. Choose PNG (default) or SVG. Set `theme`, `width`, `background-color`, or `pixel-ratio` to customize the result. Enable the package with `--extension diagram`. + +== a2s + +Render `[a2s]` blocks and `a2s::chart.txt[]` files with `--a2s PATH`. SVG is the default. Use `format=txt` for the original text, `scalex` and `scaley` for dimensions, or `noblur=true` for crisp edges. Enable the package with `--extension diagram`. + +== svgbob + +Render `[svgbob]` blocks and `svgbob::chart.bob[]` files with `--svgbob PATH`. Choose SVG or literal text. The SVG renderer accepts `font-family`, `font-size`, `stroke-width`, and `scale`. Enable the package with `--extension diagram`. + +== syntrax + +Render `[syntrax]` blocks and `syntrax::chart.spec[]` files with `--syntrax PATH`. Choose PNG or SVG. Use `heading`, `scale`, `style-file`, and `transparent=true` to customize a railroad diagram. Enable the package with `--extension diagram`. + +== diagrams + +Render `[diagrams]` blocks and `diagrams::chart.py[]` files with `--diagrams-python PATH`. Render Python diagrams as PNG (default), SVG, or PDF with an interpreter that has the diagrams package installed. Enable the package with `--extension diagram`. + +== ditaa + +Render `[ditaa]` blocks and `ditaa::chart.ditaa[]` files with `--ditaa PATH`. Choose PNG (default), SVG, or literal text. Set `round-corners=true`, `shadows=false`, or `scale` to change the drawing. Enable the package with `--extension diagram`. + +== tape + +Render `[tape]` blocks and `tape::chart.tape[]` files with `--vhs PATH`. GIF is the default. SVG recording requires a VHS build with SVG support, such as the agentstation fork. Tape scripts run in unsafe mode. Enable the package with `--extension diagram`. + +== gnuplot + +Render `[gnuplot]` blocks and `gnuplot::chart.gp[]` files with `--gnuplot PATH`. Choose PNG, SVG, GIF, or a literal text plot. Set `width` and `height` together to select a terminal size. Enable the package with `--extension diagram`. + +== umlet + +Render `[umlet]` blocks and `umlet::chart.uxf[]` files with `--umlet PATH`. Choose SVG (default), PNG, PDF, or GIF using a UMLet command-line launcher. Enable the package with `--extension diagram`. + +== bpmn + +Render `[bpmn]` blocks and `bpmn::chart.bpmn[]` files with `--bpmn-js PATH`. Choose PNG (default), SVG, PDF, or JPEG. Set `width` and `height` to select the canvas size. Enable the package with `--extension diagram`. + +== mermaid + +Render `[mermaid]` blocks and `mermaid::chart.mmd[]` files with `--mmdc PATH`. Choose PNG or SVG and set `theme`, `scale`, or a local `config` file. Enable the package with `--extension diagram`. For SVGs with a nonzero viewBox origin, acdc uses the declared width and height. Asciidoctor Diagram 3.2.1 subtracts the origin from those dimensions. + +== oxdraw + +Render `[oxdraw]` blocks and `oxdraw::chart.mmd[]` files with `--oxdraw PATH`. SVG is the default. Use `background` and `scale` to change the output. Enable the package with `--extension diagram`. + +== lilypond + +Render `[lilypond]` blocks and `lilypond::chart.ly[]` files with `--lilypond PATH`. The output is a cropped PNG or PDF score. Set `resolution` to select the raster resolution. Enable the package with `--extension diagram`. + +== erd + +Render `[erd]` blocks and `erd::chart.erd[]` files with `--erd PATH`. Configure Graphviz with `--graphviz-dot PATH`. The ERD renderer produces DOT and Graphviz writes the final PNG or SVG. Enable the package with `--extension diagram`. + +== penrose + +Render `[penrose]` blocks and `penrose::chart.substance[]` files with `--roger PATH`. Provide `domain_file` and `style_file` relative to the diagram source. Use `variation` to choose a layout. Enable the package with `--extension diagram`. + +== plantuml + +Render `[plantuml]` blocks and `plantuml::chart.puml[]` files with `--plantuml PATH`. Choose PNG, SVG, ASCII `atxt`, or Unicode `txt` and `utxt`. Local includes resolve from the diagram directory. Configure Graphviz with `--graphviz-dot` or use the built-in Smetana layout. Enable the package with `--extension diagram`. + +== salt + +Render `[salt]` blocks and `salt::chart.salt[]` files with `--plantuml PATH`. Supply the PlantUML executable to render Salt wireframes as PNG, SVG, or text. Enable the package with `--extension diagram`. + +== vega + +Render `[vega]` blocks and `vega::chart.json[]` files with `--vg2svg PATH`. SVG uses `--vg2svg`. Supply `--vg2png PATH` for PNG and `--vl2vg PATH` for Vega-Lite specifications. Enable the package with `--extension diagram`. + +== vegalite + +Render `[vegalite]` blocks and `vegalite::chart.json[]` files with `--vl2vg PATH`. Supply the Vega SVG renderer with `--vg2svg PATH`. The compiler feeds its Vega specification to the selected SVG or PNG renderer. Enable the package with `--extension diagram`. + +== Meme + +Caption local images with `meme::photo.jpg[Top,Bottom]` and `--extension diagram --magick PATH`. PNG is the default. Use `format=gif` for GIF and `opts=noupcase` to preserve letter case. The third and fourth positional attributes set the output target and format. Use ` // ` to split a caption across lines. Both ImageMagick 7 `magick` and ImageMagick 6 `convert` accept this command line. + +== Renderer attributes + +External renderers registered through the renderer API accept case-insensitive format names. Use `jpg` for JPEG or `literal` for text when the renderer supports that format. +Document attributes such as `:svgbob-option-scale:`, `:ditaa-option-round-corners:`, `:plantumlconfig:`, and `:syntrax-style:` set defaults for their renderers. +PlantUML and Salt also accept `opts="smetana,debug"` on a diagram. + +== Verification + +With bytefield-svg 1.12.0, acdc and Asciidoctor Diagram 3.2.1 rendered a packet header block and a payload file as 681 × 32 SVGs. The field outlines and labels, image targets, alternative text, and numbered captions matched. + +With GoAT 0.5.1, acdc and Asciidoctor Diagram 3.2.1 rendered ASCII routes from a block and a local file as 152 × 58 SVGs. The shapes, light and dark colors, image targets, alternative text, and numbered captions matched. + +With Pikchr 1.0 (20250319161943), acdc and Asciidoctor Diagram 3.2.1 rendered a two-box exchange as 292 × 76 SVGs from both a block and a local file macro. Image targets, labels, and figure captions matched. Both reported the renderer’s unrecognized-token diagnostic for malformed input. + +With dpic 2023.06.01, acdc and Asciidoctor Diagram 3.2.1 rendered a two-box picture as a 195 × 51 SVG from both a bare block and a file macro. Image targets, labels, and figure captions matched. For a file already ending in `.PE`, acdc rendered the same picture. Asciidoctor Diagram 3.2.1 appended a second `.PE` and dpic reported a syntax error. + +With mscgen 0.20, acdc and Asciidoctor Diagram 3.2.1 rendered the same two-entity request and response chart as a 600 × 102 PNG block and a 600 × 78 SVG file macro. The image targets, alternative text, and numbered figure captions matched. + +Graphviz 14.1.2 rendered the same DOT graph with the `dot` layout through acdc and Asciidoctor Diagram 3.2.1. The HTML image paths, alternative text, and dimensions matched for PNG, SVG, and PDF. +For `graphviz::graphs/chart.dot[svg,alt="*Graph*"]`, both CLIs linked `chart.svg`, preserved the literal asterisks in the alternative text, and numbered the titled image as a figure. + +The WaveDrom adapter uses the file-to-file protocol from https://github.com/nlopes/acdc/pull/451[acdc-diagram]. +The acceptance fixture reproduces the https://github.com/riscv/riscv-high-assurance-cryptography/blob/6b82dbaf0096747c8acee1749a1e1c188474f478/src/ace-ISA-unpriv.adoc#L1184-L1193[RISC-V ACE register diagram for ace.load], licensed under https://creativecommons.org/licenses/by/4.0/[CC BY 4.0]. +It was verified with `wavedrom-cli` 3.2.0. To run the real-renderer test: + +[source,console] +---- +ACDC_WAVEDROM_CLI=/absolute/path/to/wavedrom-cli cargo nextest run -p acdc-diagram --all-features --run-ignored only -E 'test(=ace_register_diagram_with_real_wavedrom_cli)' +---- + +The https://github.com/riscv/riscv-high-assurance-cryptography/blob/6b82dbaf0096747c8acee1749a1e1c188474f478/src/ace-ISA-unpriv.adoc#L513-L587[ACE state diagram fixture] is extracted from a comment in the same CC BY 4.0 source. +Install the TeX packages for standalone, TikZ, and fontspec and make the four https://github.com/riscv/docs-resources/tree/2aef34ec803cf3475376172bac78a35d5801cb21/fonts[Petrona Light and Medium upright and italic font files] available to LuaLaTeX. +The reference comparison used LuaHBTeX 1.24.0, pdf2svg 0.2.4, and Asciidoctor Diagram 3.2.1 configured to run the same LuaLaTeX engine with shell escape disabled. +To verify both formats with the real tools: + +[source,console] +---- +ACDC_LUALATEX=/absolute/path/to/lualatex ACDC_PDF2SVG=/absolute/path/to/pdf2svg cargo nextest run -p acdc-diagram --all-features --run-ignored only -E 'test(=ace_state_diagram_with_real_lualatex)' +---- + +=== PDF conversion + +The November 2026 comparison used acdc CLI 0.3.0 and Asciidoctor PDF 2.3.19 with Asciidoctor 2.0.26 and Asciidoctor Diagram 3.2.1. +Both backends rendered the ACE register and state machine from the fixtures above in a single document, using wavedrom-cli 3.2.0, LuaHBTeX 1.24.0 with shell escape disabled, and pdf2svg 0.2.4. + +With SVG for both figures, each PDF had one page. The register labels (including `ace.load`, `context`, and `immed12`) were selectable text. +Both PDFs retained the state machine as vector paths and numbered the captions _Figure 1. ACE register_ and _Figure 2. ACE state machine_. +Switching just the register to PNG embedded an 800 × 84 image with an alpha mask in each PDF. The page layouts gave the raster different displayed widths (127 ppi in acdc and 115 ppi in Asciidoctor PDF). diff --git a/extensions/diagram/src/asset.rs b/extensions/diagram/src/asset.rs new file mode 100644 index 000000000..3c3ab37f8 --- /dev/null +++ b/extensions/diagram/src/asset.rs @@ -0,0 +1,328 @@ +use std::{ + fs, + io::{self, BufReader, Read as _, Seek as _}, + path::Path, + process::{Command, Stdio}, + time::{Duration, Instant}, +}; + +use svgtypes::{Length, LengthUnit, ViewBox}; + +pub(super) const MAX_BYTES: u64 = 16 * 1024 * 1024; + +pub(super) struct ImageSize { + pub(super) width: f64, + pub(super) height: f64, +} + +impl ImageSize { + fn from_svg_root(root: roxmltree::Node<'_, '_>) -> Option { + let pixels = |name| { + let length: Length = root.attribute(name)?.trim().parse().ok()?; + let factor = match length.unit { + LengthUnit::None | LengthUnit::Px => 1.0, + // Match Asciidoctor Diagram's conversion of pdf2svg's TeX points. + LengthUnit::Pt => 1.33, + LengthUnit::In => 96.0, + LengthUnit::Cm => 96.0 / 2.54, + LengthUnit::Mm => 96.0 / 25.4, + LengthUnit::Pc => 16.0, + LengthUnit::Em | LengthUnit::Ex | LengthUnit::Percent => return None, + }; + let value = length.number * factor; + (value.is_finite() && value >= 0.0).then_some(value) + }; + if let (Some(width), Some(height)) = (pixels("width"), pixels("height")) { + return Some(Self { width, height }); + } + let view_box: ViewBox = root.attribute("viewBox")?.parse().ok()?; + Some(Self { + width: view_box.w, + height: view_box.h, + }) + } +} + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum Format { + Atxt, + Utxt, + Txt, + Gif, + Jpeg, + Svg, + Png, + Pdf, +} + +impl Format { + pub(super) fn extension(self) -> &'static str { + match self { + Self::Atxt => "atxt", + Self::Utxt => "utxt", + Self::Txt => "txt", + Self::Gif => "gif", + Self::Jpeg => "jpeg", + Self::Svg => "svg", + Self::Png => "png", + Self::Pdf => "pdf", + } + } + + pub(super) fn matches_name(self, value: &str) -> bool { + let value = value.trim(); + value.eq_ignore_ascii_case(self.extension()) + || (self == Self::Jpeg && value.eq_ignore_ascii_case("jpg")) + || (self == Self::Txt && value.eq_ignore_ascii_case("literal")) + } + + pub(super) fn validate(self, path: &Path) -> io::Result> { + let meta = fs::symlink_metadata(path)?; + if !meta.is_file() || meta.len() > MAX_BYTES { + return Err(io::Error::other( + "expected a regular diagram file of at most 16 MiB", + )); + } + let mut file = fs::File::open(path)?; + match self { + Self::Txt | Self::Atxt | Self::Utxt => { + Err(io::Error::other("text output requires a literal block")) + } + Self::Gif => validate_raster(file, image::ImageFormat::Gif).map(Some), + Self::Jpeg => validate_raster(file, image::ImageFormat::Jpeg).map(Some), + Self::Svg => { + let mut svg = String::new(); + file.take(MAX_BYTES + 1).read_to_string(&mut svg)?; + if svg.len() as u64 > MAX_BYTES { + return Err(io::Error::other("invalid SVG output")); + } + let document = roxmltree::Document::parse_with_options( + &svg, + roxmltree::ParsingOptions { + allow_dtd: declares_standard_svg(&svg), + ..Default::default() + }, + ) + .map_err(io::Error::other)?; + let root = document.root_element(); + if !root.has_tag_name(("http://www.w3.org/2000/svg", "svg")) { + return Err(io::Error::other("invalid SVG output")); + } + Ok(ImageSize::from_svg_root(root)) + } + Self::Png => validate_png(file).map(Some), + Self::Pdf => { + let mut signature = [0; 5]; + file.read_exact(&mut signature)?; + file.seek(io::SeekFrom::Start(meta.len().saturating_sub(1024)))?; + let mut tail = Vec::new(); + file.take(1024).read_to_end(&mut tail)?; + if &signature != b"%PDF-" || !tail.trim_ascii_end().ends_with(b"%%EOF") { + return Err(io::Error::other("invalid PDF output")); + } + Ok(None) + } + } + } +} + +// Graphviz and blockdiag emit external SVG declarations. Only enable DTD parsing for +// that exact prolog (without an internal subset), with no external entity resolver. +fn declares_standard_svg(svg: &str) -> bool { + let svg = svg.trim_start_matches('\u{feff}').trim_start(); + let mut prolog = svg + .strip_prefix("")) + .map_or(svg, |(_, rest)| rest.trim_start()); + while let Some(comment) = prolog.strip_prefix("") else { + return false; + }; + prolog = rest.trim_start(); + } + prolog.strip_prefix("')) + .is_some_and(|(decl, _)| [ + r#"svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd""#, + r#"svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd""#, + ].iter().any(|known| decl.replace('\'', "\"").split_ascii_whitespace().eq(known.split_ascii_whitespace()))) +} + +// Check the raster and its end marker before publishing, without storing a full frame. +fn validate_raster(file: fs::File, format: image::ImageFormat) -> io::Result { + let mut reader = image::ImageReader::with_format(BufReader::new(file), format); + let mut limits = image::Limits::default(); + limits.max_alloc = Some(64 * 1024 * 1024); + reader.limits(limits); + let raster = reader.decode().map_err(io::Error::other)?; + Ok(ImageSize { + width: f64::from(raster.width()), + height: f64::from(raster.height()), + }) +} + +fn validate_png(file: fs::File) -> io::Result { + let invalid = |e: png::DecodingError| { + io::Error::new( + io::ErrorKind::InvalidData, + format!("invalid PNG output: {e}"), + ) + }; + let mut reader = png::Decoder::new(BufReader::new(file)) + .read_info() + .map_err(invalid)?; + if reader + .output_buffer_size() + .is_none_or(|bytes| bytes > png::Limits::default().bytes) + { + return Err(io::Error::other( + "PNG raster exceeds the decoder size limit", + )); + } + while reader.next_row().map_err(invalid)?.is_some() {} + reader.finish().map_err(invalid)?; + let (width, height) = reader.info().size(); + Ok(ImageSize { + width: f64::from(width), + height: f64::from(height), + }) +} + +pub(super) fn scratch_dir(dir: &Path) -> io::Result { + let mut scratch = tempfile::Builder::new(); + scratch.prefix(".acdc-diagram-"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + scratch.permissions(fs::Permissions::from_mode(0o700)); + } + scratch.tempdir_in(dir) +} + +pub(super) fn read_text(path: &Path) -> io::Result { + let meta = fs::symlink_metadata(path)?; + if !meta.is_file() || meta.len() > MAX_BYTES { + return Err(io::Error::other( + "expected a regular text file of at most 16 MiB", + )); + } + let mut text = String::new(); + fs::File::open(path)? + .take(MAX_BYTES + 1) + .read_to_string(&mut text)?; + if text.len() as u64 > MAX_BYTES { + return Err(io::Error::other("renderer text exceeds 16 MiB")); + } + Ok(text) +} + +pub(super) fn publish( + dir: &Path, + filename: &str, + format: Format, + generate: impl FnOnce(&Path, &Path) -> io::Result<()>, +) -> io::Result> { + let scratch = scratch_dir(dir)?; + let output = scratch + .path() + .join(format!("output.{}", format.extension())); + generate(scratch.path(), &output)?; + let size = format.validate(&output)?; + fs::rename(output, dir.join(filename))?; + Ok(size) +} + +pub(super) fn run(command: &mut Command, dir: &Path, tool: &str) -> io::Result<()> { + run_redirected(command, dir, tool, Stdio::null(), None) +} + +pub(super) fn run_with_source( + command: &mut Command, + dir: &Path, + tool: &str, + scratch: &Path, + source: &str, + stdout: Option<&Path>, +) -> io::Result<()> { + let path = scratch.join("stdin"); + fs::write(&path, source.as_bytes())?; + run_redirected(command, dir, tool, fs::File::open(path)?.into(), stdout) +} + +/// Stream renderer stdout directly to the unpublished asset. +pub(super) fn run_to_file( + command: &mut Command, + dir: &Path, + tool: &str, + output: &Path, +) -> io::Result<()> { + run_redirected(command, dir, tool, Stdio::null(), Some(output)) +} + +fn run_redirected( + command: &mut Command, + dir: &Path, + tool: &str, + stdin: Stdio, + output: Option<&Path>, +) -> io::Result<()> { + let output = output.map(fs::File::create_new).transpose()?; + let stdout = match &output { + Some(file) => Stdio::from(file.try_clone()?), + None => Stdio::null(), + }; + let mut child = command + .current_dir(dir) + .stdin(stdin) + .stdout(stdout) + .stderr(Stdio::null()) + .spawn()?; + let deadline = Instant::now() + Duration::from_secs(30); + let error = loop { + match child.try_wait() { + Ok(Some(status)) if status.success() => return Ok(()), + Ok(Some(status)) => { + return Err(io::Error::other(format!("{tool} exited with {status}"))); + } + Err(error) => break error, + Ok(None) => {} + } + if let Some(file) = &output { + match file.metadata() { + Ok(meta) if meta.len() > MAX_BYTES => { + break io::Error::other(format!("{tool} output exceeds 16 MiB")); + } + Err(error) => break error, + Ok(_) => {} + } + } + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + break io::Error::new( + io::ErrorKind::TimedOut, + format!("{tool} exceeded 30 seconds"), + ); + } + std::thread::sleep(remaining.min(Duration::from_millis(10))); + }; + let _ = child.kill(); + child.wait()?; + Err(error) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn svg_11_declaration_with_internal_subset_is_rejected() -> io::Result<()> { + let dir = tempfile::tempdir()?; + let path = dir.path().join("graph.svg"); + fs::write( + &path, + r#""#, + )?; + assert!(Format::Svg.validate(&path).is_err()); + Ok(()) + } +} diff --git a/extensions/diagram/src/bytefield.rs b/extensions/diagram/src/bytefield.rs new file mode 100644 index 000000000..81c3de13e --- /dev/null +++ b/extensions/diagram/src/bytefield.rs @@ -0,0 +1,63 @@ +//! Render byte-field diagrams with `bytefield-svg`. + +use std::{io, path::Path, process::Command}; + +use acdc_parser::extensions::{BlockBuilder, BlockMacro, BlockStyle}; + +use super::{DiagramInput, OutputDirectories, asset, executable, file_macro, render_svg, style}; + +/// Register the `bytefield` listing and literal block style with a caller-selected executable. +/// +/// # Errors +/// Returns an error if the executable or an output directory cannot be resolved. +pub fn bytefield<'a>( + tool: &Path, + output_dir: impl Into>, +) -> io::Result { + let tool = executable(std::path::absolute(tool)?)?; + style("bytefield", output_dir.into(), move |roots, input| { + render(&tool, roots.embedded, roots, input) + }) +} + +/// Register `bytefield::file.edn[]` using the parser's local source loader. +/// +/// # Errors +/// Returns an error if the executable or an output directory cannot be resolved. +pub fn bytefield_file<'a>( + tool: &Path, + output_dir: impl Into>, +) -> io::Result { + let tool = executable(std::path::absolute(tool)?)?; + file_macro( + "bytefield", + output_dir.into(), + &["bytefield-svg"], + move |dir, roots, input| render(&tool, dir, roots, input), + ) +} + +fn render( + tool: &Path, + dir: &Path, + roots: OutputDirectories<'_>, + input: &DiagramInput<'_>, +) -> Result { + render_svg( + "bytefield", + "bytefield-svg", + roots, + input, + &[], + |source, scratch, output| { + asset::run_with_source( + Command::new(tool).arg("--output").arg(output), + dir, + "bytefield-svg", + scratch, + source, + None, + ) + }, + ) +} diff --git a/extensions/diagram/src/dpic.rs b/extensions/diagram/src/dpic.rs new file mode 100644 index 000000000..3e32a260d --- /dev/null +++ b/extensions/diagram/src/dpic.rs @@ -0,0 +1,89 @@ +//! PIC diagrams rendered by dpic in its safe SVG mode. + +use std::{ + fs, + io::{self, Write as _}, + path::Path, + process::Command, +}; + +use acdc_parser::extensions::{BlockBuilder, BlockMacro, BlockStyle}; + +use super::{DiagramInput, OutputDirectories, asset, executable, file_macro, render_svg, style}; + +/// Register the `dpic` listing and literal block style with a caller-selected executable. +/// +/// # Errors +/// Returns an error if the executable or an output directory cannot be resolved. +pub fn dpic<'a>( + tool: &Path, + output_dir: impl Into>, +) -> io::Result { + let tool = executable(std::path::absolute(tool)?)?; + style("dpic", output_dir.into(), move |roots, input| { + render(&tool, roots.embedded, roots, input) + }) +} + +/// Register the `dpic::file.pic[]` macro using the parser's local source loader. +/// +/// # Errors +/// Returns an error if the executable or an output directory cannot be resolved. +pub fn dpic_file<'a>( + tool: &Path, + output_dir: impl Into>, +) -> io::Result { + let tool = executable(std::path::absolute(tool)?)?; + file_macro( + "dpic", + output_dir.into(), + &["dpic"], + move |dir, roots, input| render(&tool, dir, roots, input), + ) +} + +fn render( + tool: &Path, + dir: &Path, + roots: OutputDirectories<'_>, + input: &DiagramInput<'_>, +) -> Result { + render_svg( + "dpic", + "dpic", + roots, + input, + &[], + |source, scratch, output| { + let path = scratch.join("input.pic"); + write_picture(&path, source)?; + asset::run_to_file( + Command::new(tool).args(["-v", "-z"]).arg(path), + dir, + "dpic", + output, + ) + }, + ) +} + +fn write_picture(path: &Path, source: &str) -> io::Result<()> { + let mut file = fs::File::create_new(path)?; + let mut lines = source.lines().filter(|line| !line.trim().is_empty()); + let first = lines.next().unwrap_or_default(); + let is_directive = |line: &str, directive: &str| { + line.strip_prefix(directive) + .is_some_and(|tail| tail.is_empty() || tail.starts_with(char::is_whitespace)) + }; + if !is_directive(first, ".PS") { + file.write_all(b".PS\n")?; + } + file.write_all(source.as_bytes())?; + if !source.ends_with('\n') { + file.write_all(b"\n")?; + } + if !is_directive(lines.next_back().unwrap_or(first), ".PE") { + file.write_all(b".PE\n")?; + } + Ok(()) +} diff --git a/extensions/diagram/src/file_macro.rs b/extensions/diagram/src/file_macro.rs new file mode 100644 index 000000000..98d6f2f9e --- /dev/null +++ b/extensions/diagram/src/file_macro.rs @@ -0,0 +1,76 @@ +use acdc_parser::{ + BlockMetadata, SubstitutionSpec, + extensions::{BlockBuilder, BlockMacro, MacroExecutionContext, MacroInvocation, MacroTarget}, +}; +use std::{io, path::Path}; + +use super::{DiagramInput, Directories, OutputDirectories, recover, require_unsafe}; + +pub(super) fn file_macro( + label: &'static str, + output_dir: OutputDirectories<'_>, + renderer_arguments: &'static [&'static str], + render: F, +) -> io::Result +where + F: Fn(&Path, OutputDirectories<'_>, &DiagramInput<'_>) -> Result + + Clone + + Send + + Sync + + 'static, +{ + let dirs = Directories::resolve(output_dir)?; + Ok(BlockMacro::new(label.to_ascii_lowercase(), move || { + let dirs = dirs.clone(); + let render = render.clone(); + move |call: &MacroInvocation<'_>, context: &mut MacroExecutionContext| { + let attrs = (&call.document_attributes).into(); + require_unsafe(label, attrs)?; + let mut metadata = BlockMetadata::new(); + metadata.attributes = call.attributes.clone(); + let options = call + .attributes + .get_string("opts") + .or_else(|| call.attributes.get_string("options")); + if let Some(options) = options.as_deref() { + metadata = metadata.with_options(options.split(',').map(str::trim).collect()); + } + if let Some(subs) = call.attributes.get_string("subs") { + metadata.substitutions = Some(SubstitutionSpec::Source( + subs.split(',').map(|part| part.trim().to_owned()).collect(), + )); + } + let file = context.read_local_target(); + let input = DiagramInput { + source_file: file.as_ref().ok().map(|(path, _)| path.as_path()), + body: file + .as_ref() + .map_or(call.source.as_ref(), |(_, text)| text.as_str()), + metadata: &metadata, + document_attributes: attrs, + }; + let result = match &file { + Ok((path, _)) => { + render(path.parent().unwrap_or(path), dirs.roots(), &input).map(|image| { + let attributes = call.named_arguments_source(|name| { + !matches!( + name, + "target" | "format" | "on-error" | "scale" | "subs" | "svg-type" + ) && (matches!(name, "width" | "height") + || !renderer_arguments.contains(&name)) + }); + if attributes.is_empty() { + image + } else { + image.with_attributes(attributes) + } + }) + } + Err(error) => Err(format!("{label} source '{}': {error}", call.target)), + }; + recover(result, label, &input, |msg| context.warn(msg)).map(Into::into) + } + }) + .with_target(MacroTarget::Required) + .with_positional_attributes(["format"])) +} diff --git a/extensions/diagram/src/goat.rs b/extensions/diagram/src/goat.rs new file mode 100644 index 000000000..31ec63a54 --- /dev/null +++ b/extensions/diagram/src/goat.rs @@ -0,0 +1,75 @@ +//! Render `GoAT` ASCII diagrams as SVG. + +use std::{io, path::Path, process::Command}; + +use acdc_parser::extensions::{BlockBuilder, BlockMacro, BlockStyle}; + +use super::{ + DiagramInput, OutputDirectories, asset, diagram_attribute, executable, file_macro, render_svg, + style, +}; + +/// Register the `goat` listing and literal block style with a caller-selected executable. +/// +/// # Errors +/// Returns an error if the executable or an output directory cannot be resolved. +pub fn goat<'a>( + tool: &Path, + output_dir: impl Into>, +) -> io::Result { + let tool = executable(std::path::absolute(tool)?)?; + style("goat", output_dir.into(), move |roots, input| { + render(&tool, roots.embedded, roots, input) + }) +} + +/// Register `goat::file.txt[]` using the parser's local source loader. +/// +/// # Errors +/// Returns an error if the executable or an output directory cannot be resolved. +pub fn goat_file<'a>( + tool: &Path, + output_dir: impl Into>, +) -> io::Result { + let tool = executable(std::path::absolute(tool)?)?; + file_macro( + "goat", + output_dir.into(), + &["goat", "svg-color-dark-scheme", "svg-color-light-scheme"], + move |dir, roots, input| render(&tool, dir, roots, input), + ) +} + +fn render( + tool: &Path, + dir: &Path, + roots: OutputDirectories<'_>, + input: &DiagramInput<'_>, +) -> Result { + let dark = diagram_attribute(input, "goat", "svg-color-dark-scheme"); + let light = diagram_attribute(input, "goat", "svg-color-light-scheme"); + let mut args = Vec::new(); + if let Some(color) = dark.as_deref() { + args.extend(["-sds", color]); + } + if let Some(color) = light.as_deref() { + args.extend(["-sls", color]); + } + render_svg( + "goat", + "goat", + roots, + input, + &args, + |source, scratch, output| { + asset::run_with_source( + Command::new(tool).args(&args), + dir, + "goat", + scratch, + source, + Some(output), + ) + }, + ) +} diff --git a/extensions/diagram/src/graphviz.rs b/extensions/diagram/src/graphviz.rs new file mode 100644 index 000000000..224e6d6ac --- /dev/null +++ b/extensions/diagram/src/graphviz.rs @@ -0,0 +1,99 @@ +//! Graphviz's stdin-to-file adapter, ported from acdc-diagram (PR #451). + +use std::{io, path::Path, process::Command}; + +use acdc_parser::{ + DocumentAttributeValue, + extensions::{BlockBuilder, BlockMacro, BlockStyle}, +}; + +use super::{ + DiagramInput, OutputDirectories, + asset::{self, Format}, + diagram_attribute, diagram_source, executable, file_macro, image, style, +}; + +/// Register the `graphviz` style with a trusted Graphviz `dot` executable. +/// Relative graph resources resolve from the caller's source image directory. +/// +/// # Errors +/// Returns an error if the executable or a configured directory cannot be resolved. +pub fn graphviz<'a>( + dot: &Path, + output_dir: impl Into>, +) -> io::Result { + // Graphviz also selects a layout from argv[0] on multi-call installations. + let dot = executable(std::path::absolute(dot)?)?; + style("Graphviz", output_dir.into(), move |roots, input| { + render(&dot, roots.embedded, roots, input) + }) +} + +/// Register the `graphviz::file.dot[format]` macro with a trusted Graphviz executable. +/// File targets use the parser's include loader and byte budget. Relative graph +/// resources resolve from the directory containing the DOT file. +/// +/// # Errors +/// Returns an error if the executable or an output directory cannot be resolved. +pub fn graphviz_file<'a>( + dot: &Path, + output_dir: impl Into>, +) -> io::Result { + let dot = executable(std::path::absolute(dot)?)?; + file_macro( + "Graphviz", + output_dir.into(), + &["layout", "dot", "graphvizdot"], + move |dir, roots, input| render(&dot, dir, roots, input), + ) +} + +fn render( + dot: &Path, + working_dir: &Path, + roots: OutputDirectories<'_>, + input: &DiagramInput<'_>, +) -> Result { + let args = &input.metadata.attributes; + let attrs = input.document_attributes; + for key in ["dot", "graphvizdot"] { + if args.get(key).is_some() || attrs.get(key).is_some() { + return Err("set the Graphviz executable when registering the style".into()); + } + } + let format = match diagram_attribute(input, "graphviz", "format").as_deref() { + None | Some("png") => Format::Png, + Some("svg") => Format::Svg, + Some("pdf") => Format::Pdf, + Some(other) => { + return Err(format!( + "unsupported Graphviz format '{other}' (expected png, svg or pdf)" + )); + } + }; + let layout = args.get_string("layout"); + let layout = layout.as_deref().or_else(|| { + attrs + .get("graphviz-layout") + .and_then(DocumentAttributeValue::text) + }); + let source = diagram_source(input); + image( + "graphviz", + roots, + input, + format, + [layout.unwrap_or_default(), "\0", source.as_ref()], + false, + |scratch, output| { + let mut cmd = Command::new(dot); + cmd.arg("-o") + .arg(output) + .arg(format!("-T{}", format.extension())); + if let Some(layout) = layout { + cmd.arg(format!("-K{layout}")); + } + asset::run_with_source(&mut cmd, working_dir, "dot", scratch, &source, None) + }, + ) +} diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs new file mode 100644 index 000000000..cd7054c20 --- /dev/null +++ b/extensions/diagram/src/lib.rs @@ -0,0 +1,540 @@ +//! Render explicitly registered diagram styles into ordinary acdc image blocks. + +use std::{ + borrow::Cow, + fs, io, + path::{Component, Path, PathBuf}, +}; + +use acdc_parser::{ + BlockMetadata, DocumentAttributeValue, SafeMode, Substitution, VERBATIM, + ast::DocumentAttributesRef, + extensions::{BlockBuilder, BlockStyle, RawBlockContext, RawBlockInput}, +}; +use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; +use sha2::{Digest, Sha256}; + +mod asset; +mod bytefield; +mod dpic; +mod file_macro; +mod goat; +mod graphviz; +mod meme; +mod msc; +mod pikchr; +pub mod renderer; +mod tikz; +mod wavedrom_cli; + +use asset::Format; +pub use bytefield::{bytefield, bytefield_file}; +pub use dpic::{dpic, dpic_file}; +use file_macro::file_macro; +pub use goat::{goat, goat_file}; +pub use graphviz::{graphviz, graphviz_file}; +pub use meme::meme; +pub use msc::{msc, msc_file}; +pub use pikchr::{pikchr, pikchr_file}; +pub use tikz::tikz; + +/// Directories used by a converter to resolve relative image references. +#[derive(Clone, Copy, Debug)] +pub struct OutputDirectories<'a> { + linked: &'a Path, + embedded: &'a Path, + imagesoutdir_base: &'a Path, +} + +impl<'a> OutputDirectories<'a> { + /// Linked images resolve from the converted file. Embedded HTML images + /// are read relative to the input document. + #[must_use] + pub const fn new(linked: &'a Path, embedded: &'a Path) -> Self { + Self { + linked, + embedded, + imagesoutdir_base: linked, + } + } + + /// Resolve a document's relative `imagesoutdir` under this existing directory. + /// By default, it resolves under the linked output directory. + #[must_use] + pub const fn with_imagesoutdir_base(mut self, base: &'a Path) -> Self { + self.imagesoutdir_base = base; + self + } +} + +impl<'a, P: AsRef + ?Sized> From<&'a P> for OutputDirectories<'a> { + fn from(dir: &'a P) -> Self { + Self::new(dir.as_ref(), dir.as_ref()) + } +} + +/// Register the `wavedrom` style for listing and literal blocks with a trusted renderer and an +/// existing output directory (the directory containing the converted document). +/// The caller installs the returned style in its registry. Rendering requires +/// [`SafeMode::Unsafe`]. The body is verbatim unless its `subs` setting enables attributes. +/// +/// # Errors +/// Returns an error if either path cannot be resolved or has the wrong file type. +pub fn wavedrom<'a>( + tool: &Path, + output_dir: impl Into>, +) -> io::Result { + let tool = executable(tool.canonicalize()?)?; + style("WaveDrom", output_dir.into(), move |root, input| { + render(&tool, root, input) + }) +} + +fn executable(tool: PathBuf) -> io::Result { + if !tool.is_file() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("expected an executable file at {}", tool.display()), + )); + } + Ok(tool) +} + +struct DiagramInput<'a> { + source_file: Option<&'a Path>, + body: &'a str, + metadata: &'a BlockMetadata<'a>, + document_attributes: DocumentAttributesRef<'a>, +} + +#[derive(Clone)] +struct Directories { + linked: PathBuf, + embedded: Option, + staging: Option, +} + +impl Directories { + fn resolve(output_dir: OutputDirectories<'_>) -> io::Result { + let directory = |path: &Path| { + let root = path.canonicalize()?; + if root.is_dir() { + Ok(root) + } else { + Err(io::Error::new( + io::ErrorKind::InvalidInput, + format!("expected an output directory at {}", path.display()), + )) + } + }; + let linked = directory(output_dir.linked)?; + let alternate_root = |path: &Path| { + (path != output_dir.linked) + .then(|| directory(path)) + .transpose() + }; + let embedded = alternate_root(output_dir.embedded)?; + let staging = alternate_root(output_dir.imagesoutdir_base)?; + Ok(Self { + linked, + embedded, + staging, + }) + } + fn roots(&self) -> OutputDirectories<'_> { + OutputDirectories::new( + &self.linked, + self.embedded.as_deref().unwrap_or(&self.linked), + ) + .with_imagesoutdir_base(self.staging.as_deref().unwrap_or(&self.linked)) + } +} + +fn style( + label: &'static str, + output_dir: OutputDirectories<'_>, + render: F, +) -> io::Result +where + F: Fn(OutputDirectories<'_>, &DiagramInput<'_>) -> Result + + Clone + + Send + + Sync + + 'static, +{ + let dirs = Directories::resolve(output_dir)?; + Ok(BlockStyle::raw( + label.to_ascii_lowercase(), + [RawBlockContext::Listing, RawBlockContext::Literal], + move || { + let dirs = dirs.clone(); + let render = render.clone(); + move |mut raw: RawBlockInput<'_>| { + let input = DiagramInput { + source_file: None, + body: raw.body, + metadata: raw.metadata, + document_attributes: raw.document_attributes, + }; + require_unsafe(label, input.document_attributes)?; + let result = render(dirs.roots(), &input); + recover(result, label, &input, |msg| raw.warn(msg)).map(Some) + } + }, + ) + .with_positional_attributes(["target", "format"])) +} + +fn require_unsafe(label: &str, attrs: DocumentAttributesRef<'_>) -> Result<(), String> { + if attrs + .get("safe-mode-name") + .and_then(DocumentAttributeValue::text) + == Some(SafeMode::Unsafe.name()) + { + Ok(()) + } else { + Err(format!( + "{label} requires unsafe mode to run the configured executable" + )) + } +} + +fn recover( + result: Result, + label: &str, + input: &DiagramInput<'_>, + warn: impl FnOnce(String), +) -> Result { + match result { + Err(error) if !abort_on_error(input, label) => { + let message = format!("Failed to generate image: {error}"); + let listing = BlockBuilder::listing(format!("{message}\n{}", diagram_source(input))) + .without_attribute("subs"); + warn(message); + Ok(listing) + } + other => other, + } +} + +fn abort_on_error(input: &DiagramInput<'_>, label: &str) -> bool { + let attrs = input.document_attributes; + input + .metadata + .attributes + .get_string("on-error") + .as_deref() + .or_else(|| { + attrs + .get(&format!("{}-on-error", label.to_ascii_lowercase())) + .and_then(DocumentAttributeValue::text) + }) + .or_else(|| { + attrs + .get("diagram-on-error") + .and_then(DocumentAttributeValue::text) + }) + == Some("abort") +} + +fn diagram_source<'a>(input: &DiagramInput<'a>) -> Cow<'a, str> { + if input + .metadata + .uses_substitution(&Substitution::Attributes, VERBATIM) + { + let attrs = input.document_attributes; + attrs.substitute_attributes(input.body, |name| attrs.get(name)) + } else { + Cow::Borrowed(input.body) + } +} + +fn diagram_attribute<'a>( + input: &DiagramInput<'a>, + renderer: &str, + key: &str, +) -> Option> { + let attrs = input.document_attributes; + input.metadata.attributes.get_string(key).or_else(|| { + attrs + .get(&format!("{renderer}-{key}")) + .or_else(|| attrs.get(&format!("diagram-{key}"))) + .map(|value| Cow::Borrowed(value.text().unwrap_or_default())) + }) +} + +fn render( + tool: &Path, + root: OutputDirectories<'_>, + input: &DiagramInput<'_>, +) -> Result { + let attrs = input.document_attributes; + let args = &input.metadata.attributes; + if args.get("wavedrom").is_some() || attrs.get("wavedrom").is_some() { + return Err("set the WaveDrom executable when registering the style".into()); + } + let format = match diagram_attribute(input, "wavedrom", "format").as_deref() { + Some("png") => Format::Png, + None | Some("svg") => Format::Svg, + Some(other) => { + return Err(format!( + "unsupported WaveDrom format '{other}' (expected svg or png)" + )); + } + }; + let source = diagram_source(input); + image( + "wavedrom", + root, + input, + format, + [source.as_ref()], + false, + |scratch, output| wavedrom_cli::render(tool, &source, format, scratch, output), + ) +} + +fn svg_option( + renderer: &str, + input: &DiagramInput<'_>, + format: Format, +) -> Result, String> { + if format != Format::Svg { + return Ok(None); + } + for option in ["inline", "interactive"] { + if (&input.metadata.options) + .into_iter() + .any(|opt| *opt == option) + { + return Ok(Some(option)); + } + } + match diagram_attribute(input, renderer, "svg-type").as_deref() { + None | Some("static") => Ok(None), + Some("inline") => Ok(Some("inline")), + Some("interactive") => Ok(Some("interactive")), + Some(other) => Err(format!( + "{renderer} unsupported SVG type '{other}' (expected static, inline or interactive)" + )), + } +} + +fn render_svg( + name: &str, + tool_attribute: &str, + roots: OutputDirectories<'_>, + input: &DiagramInput<'_>, + arguments: &[&str], + generate: impl FnOnce(&str, &Path, &Path) -> io::Result<()>, +) -> Result { + if input.metadata.attributes.get(tool_attribute).is_some() + || input.document_attributes.get(tool_attribute).is_some() + { + return Err(format!( + "set the {tool_attribute} executable when registering the diagram" + )); + } + if let Some(format) = diagram_attribute(input, name, "format").as_deref() + && format != "svg" + { + return Err(format!( + "unsupported {name} format '{format}' (expected svg)" + )); + } + let source = diagram_source(input); + image( + name, + roots, + input, + Format::Svg, + arguments + .iter() + .flat_map(|arg| [*arg, "\0"]) + .chain([source.as_ref()]), + false, + |scratch, output| generate(&source, scratch, output), + ) +} + +fn image_filename<'a>( + name: &str, + target: &str, + format: Format, + identity: impl IntoIterator, +) -> Result { + if target.is_empty() { + let mut digest = Sha256::new(); + for part in identity { + digest.update(part); + } + Ok(format!( + "{name}-{}.{}", + URL_SAFE_NO_PAD.encode(digest.finalize()), + format.extension() + )) + } else { + if !target.split('/').all(|part| { + !part.is_empty() + && part + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_')) + }) { + return Err(format!( + "{name} target must be a relative path with nonempty segments containing only ASCII letters, digits, hyphens, or underscores" + )); + } + Ok(format!("{target}.{}", format.extension())) + } +} + +fn image<'a>( + name: &str, + roots: OutputDirectories<'_>, + input: &DiagramInput<'_>, + format: Format, + identity: impl IntoIterator, + native_scale: bool, + generate: impl FnOnce(&Path, &Path) -> io::Result<()>, +) -> Result { + let attrs = input.document_attributes; + let args = &input.metadata.attributes; + let authored_target = args.get_string("target"); + let target = authored_target + .as_deref() + .or_else(|| input.source_file?.file_stem()?.to_str()) + .unwrap_or_default(); + let image_target = image_filename(name, target, format, identity)?; + let backend = attrs + .get("backend") + .and_then(DocumentAttributeValue::text) + .unwrap_or_default(); + let option = svg_option(name, input, format)?; + let embedded = backend.starts_with("html") + && (attrs.get("data-uri").is_some() || option == Some("inline")); + let staging = attrs.get("imagesoutdir"); + let (root, attr_name, relative) = if let Some(value) = staging { + (roots.imagesoutdir_base, "imagesoutdir", value.text()) + } else { + let root = if embedded { + roots.embedded + } else { + roots.linked + }; + ( + root, + "imagesdir", + attrs + .get("imagesdir") + .and_then(DocumentAttributeValue::text), + ) + }; + let dir = image_directory(root.to_owned(), relative.unwrap_or_default()) + .map_err(|e| format!("{name} {attr_name}: {e}"))?; + let (parent, filename) = image_target.rsplit_once('/').unwrap_or(("", &image_target)); + let dir = image_directory(dir, parent).map_err(|e| format!("{name} target: {e}"))?; + if let Some(source) = input.source_file { + let destination = dir.join(filename); + if destination == source || source.canonicalize().is_ok_and(|path| path == destination) { + return Err(format!("{name} output would overwrite its source file")); + } + } + let physical_target = if staging.is_some() && (embedded || backend == "pdf") { + Some(staged_file_url(&dir.join(filename))?) + } else if staging.is_some() && backend == "terminal" { + Some( + dir.join(filename) + .into_os_string() + .into_string() + .map_err(|_| format!("{name} terminal image path must be UTF-8"))?, + ) + } else { + None + }; + let size = + asset::publish(&dir, filename, format, generate).map_err(|e| format!("{name}: {e}"))?; + let mut image = BlockBuilder::image(physical_target.unwrap_or(image_target)); + if let Some(option) = option + && !(&input.metadata.options) + .into_iter() + .any(|opt| *opt == option) + { + image = image.with_attributes(format!("opts={option}")); + } + let mut defaults = Vec::new(); + if authored_target.as_deref().unwrap_or_default().is_empty() { + defaults.push("alt=Diagram".to_owned()); + } + if backend.starts_with("html") + && let Some(size) = size + { + let scale = if native_scale { + 1.0 + } else { + args.get_string("scale") + .and_then(|value| value.parse::().ok()) + .filter(|scale| scale.is_finite() && *scale >= 0.0) + .unwrap_or(1.0) + }; + let width = (size.width * scale).trunc(); + let height = (size.height * scale).trunc(); + if width.is_finite() && height.is_finite() { + defaults.push(format!("width={width},height={height}")); + } + } + Ok(if defaults.is_empty() { + image + } else { + image.with_default_attributes(defaults.join(",")) + }) +} + +#[cfg(any( + unix, + windows, + target_os = "redox", + target_os = "wasi", + target_os = "hermit" +))] +fn staged_file_url(path: &Path) -> Result { + url::Url::from_file_path(path) + .map(Into::into) + .map_err(|()| format!("cannot construct a file URL for {}", path.display())) +} + +#[cfg(not(any( + unix, + windows, + target_os = "redox", + target_os = "wasi", + target_os = "hermit" +)))] +fn staged_file_url(_: &Path) -> Result { + Err("local file URLs are not supported on this platform".into()) +} + +fn image_directory(mut dir: PathBuf, relative: &str) -> io::Result { + if relative.contains([':', '\\', '#', '?', '%']) { + return Err(io::Error::other("expected a local relative directory")); + } + let path = Path::new(relative); + for component in path.components() { + match component { + Component::CurDir => continue, + Component::Normal(name) => dir.push(name), + Component::Prefix(_) | Component::RootDir | Component::ParentDir => { + return Err(io::Error::other("expected a local relative directory")); + } + } + match fs::create_dir(&dir) { + Ok(()) => {} + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { + if !fs::symlink_metadata(&dir)?.file_type().is_dir() { + return Err(io::Error::other("path must contain only real directories")); + } + } + Err(e) => return Err(e), + } + } + Ok(dir) +} diff --git a/extensions/diagram/src/meme.rs b/extensions/diagram/src/meme.rs new file mode 100644 index 000000000..e42965be6 --- /dev/null +++ b/extensions/diagram/src/meme.rs @@ -0,0 +1,290 @@ +//! Caption a local image using an explicitly configured `ImageMagick` executable. +use super::{ + DiagramInput, Directories, OutputDirectories, + asset::{self, Format}, + diagram_attribute, executable, image, recover, require_unsafe, +}; +use acdc_parser::{ + BlockMetadata, + extensions::{BlockBuilder, BlockMacro, MacroExecutionContext, MacroInvocation, MacroTarget}, +}; +use std::{ + borrow::Cow, + io, + path::{Path, PathBuf}, + process::Command, +}; + +/// Register `meme::background.jpg[top,bottom,target,format]` with `ImageMagick`. +/// +/// # Errors +/// Returns an error if the program or configured output directories cannot be resolved. +pub fn meme<'a>(tool: &Path, output: impl Into>) -> io::Result { + let tool = executable(std::path::absolute(tool)?)?; + let dirs = Directories::resolve(output.into())?; + Ok(BlockMacro::new("meme", move || { + let tool = tool.clone(); + let dirs = dirs.clone(); + move |call: &MacroInvocation<'_>, context: &mut MacroExecutionContext| { + let attrs = (&call.document_attributes).into(); + require_unsafe("meme", attrs)?; + let mut metadata = BlockMetadata::new(); + metadata.attributes = call.attributes.clone(); + // Anonymous memes sharing a background can have different captions. + metadata + .attributes + .insert_if_absent("target".into(), "".into()); + let input = DiagramInput { + metadata: &metadata, + source_file: None, + body: call.source.as_ref(), + document_attributes: attrs, + }; + let result = render(&tool, dirs.roots(), call.target.as_ref(), &input).map(|block| { + let attributes = call.named_arguments_source(|k| { + !matches!( + k, + "format" | "target" | "top" | "bottom" | "on-error" | "background" + ) && !CAPTION_ATTRIBUTES.contains(&k) + }); + if attributes.is_empty() { + block + } else { + block.with_attributes(attributes) + } + }); + recover(result, "meme", &input, |m| context.warn(m)).map(Into::into) + } + }) + .with_target(MacroTarget::Required) + .with_positional_attributes(["top", "bottom", "target", "format"])) +} +const CAPTION_ATTRIBUTES: &[&str] = &[ + "font", + "fillcolor", + "fill-color", + "strokecolor", + "stroke-color", + "strokewidth", + "stroke-width", + "top-height", + "bottom-height", + "height-fraction", +]; +fn render( + tool: &Path, + roots: OutputDirectories<'_>, + background: &str, + input: &DiagramInput<'_>, +) -> Result { + for key in ["magick", "convert", "identify"] { + if input.metadata.attributes.get(key).is_some() + || input.document_attributes.get(key).is_some() + { + return Err("set the ImageMagick executable when registering the diagram".into()); + } + } + let format = match diagram_attribute(input, "meme", "format").as_deref() { + None | Some("png") => Format::Png, + Some("gif") => Format::Gif, + Some(other) => { + return Err(format!( + "unsupported meme format '{other}' (expected png or gif)" + )); + } + }; + let background_file = background_path(roots.embedded, background, input)?; + let options: Vec<_> = ["top", "bottom"] + .into_iter() + .chain(CAPTION_ATTRIBUTES.iter().copied()) + .filter_map(|k| diagram_attribute(input, "meme", k).map(|v| (k, v))) + .collect(); + let flags = input + .metadata + .attributes + .get_string("opts") + .or_else(|| input.metadata.attributes.get_string("options")); + let noupcase = flags + .as_deref() + .is_some_and(|v| v.split(',').any(|s| s.trim() == "noupcase")); + let identity = [ + background, + "\0", + if noupcase { "literal" } else { "uppercase" }, + "\0", + ] + .into_iter() + .chain( + options + .iter() + .flat_map(|(k, v)| [*k, "\0", v.as_ref(), "\0"]), + ); + let resolved = DiagramInput { + source_file: Some(&background_file), + ..*input + }; + image( + "meme", + roots, + &resolved, + format, + identity, + false, + |scratch, output| { + compose_captions( + tool, + roots.embedded, + &background_file, + scratch, + output, + &options, + noupcase, + ) + }, + ) +} + +fn background_path( + root: &Path, + background: &str, + input: &DiagramInput<'_>, +) -> Result { + let relative = Path::new(background); + if background.is_empty() + || background.contains([':', '\\']) + || relative.components().any(|c| { + !matches!( + c, + std::path::Component::Normal(_) | std::path::Component::CurDir + ) + }) + { + return Err("meme background must be a local relative image path".to_owned()); + } + let imagesdir = input + .document_attributes + .get("imagesdir") + .and_then(acdc_parser::DocumentAttributeValue::text) + .unwrap_or_default(); + let background_file = root + .join(imagesdir) + .join(relative) + .canonicalize() + .map_err(|e| format!("meme background '{background}': {e}"))?; + if !background_file.starts_with(root) || !background_file.is_file() { + return Err("meme background must be a local file in the source directory".into()); + } + Ok(background_file) +} + +fn dimensions( + tool: &Path, + background_file: &Path, + dir: &Path, + scratch: &Path, +) -> io::Result<(u32, u32)> { + let dimensions = scratch.join("dimensions"); + asset::run_to_file( + Command::new(tool) + .arg(background_file) + .args(["-format", "%w %h", "info:"]), + dir, + "ImageMagick", + &dimensions, + )?; + let dimensions = asset::read_text(&dimensions)?; + let (width, height) = dimensions + .trim() + .split_once(' ') + .ok_or_else(|| io::Error::other("invalid background dimensions"))?; + let width = width.parse::().map_err(io::Error::other)?; + let height = height.parse::().map_err(io::Error::other)?; + Ok((width, height)) +} + +fn compose_captions( + tool: &Path, + dir: &Path, + background_file: &Path, + scratch: &Path, + output: &Path, + options: &[(&str, Cow<'_, str>)], + noupcase: bool, +) -> io::Result<()> { + let get = |key: &str| { + options + .iter() + .find(|(k, _)| *k == key) + .map(|(_, v)| v.as_ref()) + }; + let (width, height) = dimensions(tool, background_file, dir, scratch)?; + let mut compose = Command::new(tool); + compose.arg(background_file); + for (key, gravity, hkey) in [ + ("top", "north", "top-height"), + ("bottom", "south", "bottom-height"), + ] { + let Some(caption) = get(key) else { continue }; + let cap_height = caption_height( + get(hkey) + .or_else(|| get("height-fraction")) + .unwrap_or("20%"), + height, + )?; + let label = if noupcase { + caption.to_owned() + } else { + caption.to_uppercase() + } + .replace(" // ", "\n"); + let path = scratch.join(format!("{key}.png")); + let mut cmd = Command::new(tool); + cmd.args([ + "-background", + "none", + "-fill", + get("fillcolor") + .or_else(|| get("fill-color")) + .unwrap_or("white"), + "-stroke", + get("strokecolor") + .or_else(|| get("stroke-color")) + .unwrap_or("black"), + "-strokewidth", + get("strokewidth") + .or_else(|| get("stroke-width")) + .unwrap_or("2"), + "-font", + get("font").unwrap_or("Impact"), + "-size", + ]) + .arg(format!("{width}x{cap_height}")) + .args(["-gravity", gravity]) + .arg(format!("label:{label}")) + .arg(&path); + asset::run(&mut cmd, dir, "ImageMagick")?; + let offset = if key == "top" { + 0 + } else { + i64::from(height) - i64::from(cap_height) + }; + compose + .arg(path) + .arg("-geometry") + .arg(format!("+0{offset:+}")) + .arg("-composite"); + } + asset::run(compose.arg(output), dir, "ImageMagick") +} +fn caption_height(value: &str, height: u32) -> io::Result { + if let Some(percent) = value.strip_suffix('%') { + let p = percent.parse::().map_err(io::Error::other)?; + u32::try_from(u64::from(height) * u64::from(p) / 100).map_err(io::Error::other) + } else { + value + .strip_suffix("px") + .unwrap_or(value) + .parse() + .map_err(io::Error::other) + } +} diff --git a/extensions/diagram/src/msc.rs b/extensions/diagram/src/msc.rs new file mode 100644 index 000000000..16cf4111c --- /dev/null +++ b/extensions/diagram/src/msc.rs @@ -0,0 +1,91 @@ +//! Message sequence charts rendered with the mscgen protocol from PR #451. + +use std::{io, path::Path, process::Command}; + +use acdc_parser::{ + DocumentAttributeValue, + extensions::{BlockBuilder, BlockMacro, BlockStyle}, +}; + +use super::{ + DiagramInput, OutputDirectories, + asset::{self, Format}, + diagram_attribute, diagram_source, executable, file_macro, image, style, +}; + +/// Register the `msc` listing and literal block style with a caller-selected executable. +/// +/// # Errors +/// Returns an error if the executable or output directories cannot be resolved. +pub fn msc<'a>( + tool: &Path, + output_dir: impl Into>, +) -> io::Result { + let tool = executable(std::path::absolute(tool)?)?; + style("msc", output_dir.into(), move |roots, input| { + render(&tool, roots.embedded, roots, input) + }) +} + +/// Register the `msc::file.msc[format]` macro using the parser's local target policy. +/// +/// # Errors +/// Returns an error if the executable or output directories cannot be resolved. +pub fn msc_file<'a>( + tool: &Path, + output_dir: impl Into>, +) -> io::Result { + let tool = executable(std::path::absolute(tool)?)?; + file_macro( + "msc", + output_dir.into(), + &["mscgen", "mscgen_js", "font"], + move |dir, roots, input| render(&tool, dir, roots, input), + ) +} + +fn render( + tool: &Path, + dir: &Path, + roots: OutputDirectories<'_>, + input: &DiagramInput<'_>, +) -> Result { + let args = &input.metadata.attributes; + let attrs = input.document_attributes; + if ["mscgen", "mscgen_js"] + .iter() + .any(|key| args.get(key).is_some() || attrs.get(key).is_some()) + { + return Err("set the mscgen executable when registering the diagram".into()); + } + let format = match diagram_attribute(input, "msc", "format").as_deref() { + None | Some("png") => Format::Png, + Some("svg") => Format::Svg, + Some(other) => { + return Err(format!( + "unsupported msc format '{other}' (expected png or svg)" + )); + } + }; + let font = args.get_string("font"); + let font = font + .as_deref() + .or_else(|| attrs.get("msc-font").and_then(DocumentAttributeValue::text)); + let source = diagram_source(input); + image( + "msc", + roots, + input, + format, + [font.unwrap_or_default(), "\0", source.as_ref()], + false, + |scratch, output| { + let mut cmd = Command::new(tool); + cmd.arg("-o").arg(output).arg("-T").arg(format.extension()); + if let Some(font) = font { + cmd.arg("-F").arg(font); + } + asset::run_with_source(cmd.arg("-"), dir, "mscgen", scratch, &source, None) + }, + ) +} diff --git a/extensions/diagram/src/pikchr.rs b/extensions/diagram/src/pikchr.rs new file mode 100644 index 000000000..329016b16 --- /dev/null +++ b/extensions/diagram/src/pikchr.rs @@ -0,0 +1,109 @@ +//! Pikchr's file-to-SVG adapter from PR #451. + +use std::{ + fs, + io::{self, BufRead as _, BufReader, Seek as _, SeekFrom}, + path::Path, + process::Command, +}; + +use acdc_parser::extensions::{BlockBuilder, BlockMacro, BlockStyle}; + +use super::{DiagramInput, OutputDirectories, asset, executable, file_macro, render_svg, style}; + +/// Register the `pikchr` listing and literal block style with a caller-selected executable. +/// +/// # Errors +/// Returns an error if the executable or an output directory cannot be resolved. +pub fn pikchr<'a>( + tool: &Path, + output_dir: impl Into>, +) -> io::Result { + let tool = executable(std::path::absolute(tool)?)?; + style("pikchr", output_dir.into(), move |roots, input| { + render(&tool, roots.embedded, roots, input) + }) +} + +/// Register `pikchr::file.pikchr[]` using the parser's local source loader. +/// +/// # Errors +/// Returns an error if the executable or an output directory cannot be resolved. +pub fn pikchr_file<'a>( + tool: &Path, + output_dir: impl Into>, +) -> io::Result { + let tool = executable(std::path::absolute(tool)?)?; + file_macro( + "pikchr", + output_dir.into(), + &["pikchr"], + move |dir, roots, input| render(&tool, dir, roots, input), + ) +} + +fn render( + tool: &Path, + dir: &Path, + roots: OutputDirectories<'_>, + input: &DiagramInput<'_>, +) -> Result { + render_svg( + "pikchr", + "pikchr", + roots, + input, + &[], + |source, scratch, output| { + let path = scratch.join("input.pikchr"); + fs::write(&path, source)?; + let result = asset::run_to_file( + Command::new(tool).arg("--svg-only").arg(path), + dir, + "pikchr", + output, + ); + match (result, output_diagnostic(output)) { + (Ok(()), Some(message)) => Err(io::Error::other(message)), + (Err(err), Some(message)) => { + Err(io::Error::new(err.kind(), format!("{err}: {message}"))) + } + (result, _) => result, + } + }, + ) +} + +// Pikchr writes parser diagnostics to stdout. Older CLIs return an HTML fragment +// with exit status zero. The shared validator handles all other non-SVG output. +fn output_diagnostic(path: &Path) -> Option { + const EXCERPT: u16 = 4096; + let metadata = fs::symlink_metadata(path).ok()?; + if !metadata.is_file() { + return None; + } + let mut reader = BufReader::with_capacity(usize::from(EXCERPT), fs::File::open(path).ok()?); + let prefix = reader.fill_buf().ok()?.trim_ascii_start(); + if prefix.starts_with(b"<") && !prefix.starts_with(b" u64::from(EXCERPT) { + reader.seek(SeekFrom::End(-i64::from(EXCERPT))).ok()?; + } + let excerpt = String::from_utf8_lossy(reader.fill_buf().ok()?); + if let Ok(doc) = roxmltree::Document::parse(excerpt.trim()) { + let message = doc + .descendants() + .filter(roxmltree::Node::is_text) + .filter_map(|node| node.text()) + .collect::(); + let message = message.trim(); + return (!message.is_empty()).then(|| message.to_owned()); + } + excerpt + .lines() + .map(str::trim) + .find(|line| line.starts_with("ERROR:")) + .map(str::to_owned) +} diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs new file mode 100644 index 000000000..cc7ba3955 --- /dev/null +++ b/extensions/diagram/src/renderer.rs @@ -0,0 +1,1003 @@ +//! External renderers registered as listing styles and local file macros. +use std::{borrow::Cow, io, path::Path, process::Command}; + +use super::{ + DiagramInput, OutputDirectories, + asset::{self, Format}, + diagram_attribute, diagram_source, executable, file_macro, image, style, +}; +use acdc_parser::extensions::{BlockBuilder, BlockMacro, BlockStyle}; + +/// A diagram language and the command line used to render it. +#[derive(Clone, Copy)] +pub struct Renderer { + name: &'static str, + tool: &'static str, + formats: &'static [Format], + attributes: &'static [&'static str], + generate: fn(&Job<'_>) -> io::Result<()>, +} + +impl Renderer { + /// Bind a listing style and local file macro to a caller-chosen executable. + /// + /// # Errors + /// Returns an error if the executable or output directory cannot be resolved. + pub fn processors<'a>( + self, + tool: &Path, + output: impl Into>, + ) -> io::Result<(BlockStyle, BlockMacro)> { + self.processors_with_tools(tool, output, &[]) + } + + /// Bind the renderer and its named companion programs to caller-chosen paths. + /// + /// # Errors + /// Returns an error if any executable or output directory cannot be resolved. + pub fn processors_with_tools<'a>( + self, + tool: &Path, + output: impl Into>, + companions: &[(&'static str, &Path)], + ) -> io::Result<(BlockStyle, BlockMacro)> { + let companions: std::sync::Arc<[_]> = companions + .iter() + .map(|&(key, path)| Ok((key, executable(std::path::absolute(path)?)?))) + .collect::>()?; + let block_companions = companions.clone(); + let tool = executable(std::path::absolute(tool)?)?; + let output = output.into(); + let block_tool = tool.clone(); + let block = style(self.name, output, move |roots, input| { + self.render(&block_tool, &block_companions, roots.embedded, roots, input) + })?; + let file = file_macro( + self.name, + output, + self.attributes, + move |dir, roots, input| self.render(&tool, &companions, dir, roots, input), + )?; + Ok((block, file)) + } + + fn option<'a>(self, input: &DiagramInput<'a>, key: &str) -> Option> { + let document = |name: &str| { + input + .document_attributes + .get(name) + .map(|value| Cow::Borrowed(value.text().unwrap_or_default())) + }; + if matches!((self.name, key), ("plantuml" | "salt", "config")) + && let Some(config) = document("plantumlconfig") + { + return Some(config); + } + diagram_attribute(input, self.name, key).or_else(|| match (self.name, key) { + ("svgbob" | "ditaa", _) => document(&format!("{}-option-{key}", self.name)), + ("syntrax", "style-file") => document("syntrax-style"), + ("salt" | "plantuml", "smetana" | "debug") => { + let enabled = (&input.metadata.options) + .into_iter() + .any(|flag| *flag == key) + || diagram_attribute(input, self.name, &format!("{key}-option")).is_some(); + enabled.then_some(Cow::Borrowed("true")) + } + _ => None, + }) + } + + fn render( + self, + tool: &Path, + companions: &[(&str, std::path::PathBuf)], + dir: &Path, + roots: OutputDirectories<'_>, + input: &DiagramInput<'_>, + ) -> Result { + if input.metadata.attributes.get(self.tool).is_some() + || input.document_attributes.get(self.tool).is_some() + { + return Err(format!( + "set the {} executable when registering the diagram", + self.tool + )); + } + let selected = diagram_attribute(input, self.name, "format"); + let format = match selected.as_deref() { + None => *self + .formats + .first() + .ok_or("renderer has no output format")?, + Some(name) => *self + .formats + .iter() + .find(|format| format.matches_name(name)) + .ok_or_else(|| { + format!( + "unsupported {} format '{name}' (expected {})", + self.name, + self.formats + .iter() + .map(|f| f.extension()) + .collect::>() + .join(", ") + ) + })?, + }; + let options: Vec<_> = self + .attributes + .iter() + .filter_map(|&key| self.option(input, key).map(|value| (key, value))) + .collect(); + let source = diagram_source(input); + let identity = options + .iter() + .flat_map(|(k, v)| [*k, "\0", v.as_ref(), "\0"]) + .chain([source.as_ref()]); + let generate = |scratch: &Path, output: &Path| { + (self.generate)(&Job { + language: self.name, + companions, + tool, + name: self.tool, + dir, + format, + source: &source, + options: &options, + scratch, + output, + }) + }; + if matches!(format, Format::Txt | Format::Atxt | Format::Utxt) { + let render = || -> io::Result { + let scratch = asset::scratch_dir(roots.embedded)?; + let output = scratch.path().join("output.txt"); + generate(scratch.path(), &output)?; + asset::read_text(&output) + }; + return render() + .map(BlockBuilder::literal) + .map_err(|e| format!("{}: {e}", self.name)); + } + image( + self.name, + roots, + input, + format, + identity, + self.attributes.contains(&"scale"), + generate, + ) + } +} + +struct Job<'a> { + language: &'static str, + companions: &'a [(&'a str, std::path::PathBuf)], + tool: &'a Path, + name: &'static str, + dir: &'a Path, + format: Format, + source: &'a str, + options: &'a [(&'static str, Cow<'a, str>)], + scratch: &'a Path, + output: &'a Path, +} + +impl Job<'_> { + fn companion(&self, name: &str) -> io::Result<&Path> { + self.companions + .iter() + .find(|(key, _)| *key == name) + .map(|(_, p)| p.as_path()) + .ok_or_else(|| { + io::Error::other(format!( + "{} requires a caller-configured {name} executable", + self.name + )) + }) + } + fn flags(&self, cmd: &mut Command, flags: &[(&str, &str)]) { + for &(attribute, flag) in flags { + if let Some(value) = self.option(attribute) { + cmd.arg(flag).arg(value); + } + } + } + + fn source_file(&self, extension: &str) -> io::Result { + let path = self.scratch.join(format!("input.{extension}")); + std::fs::write(&path, self.source)?; + Ok(path) + } + fn run(&self, command: &mut Command) -> io::Result<()> { + asset::run(command, self.dir, self.name) + } + + fn option(&self, key: &str) -> Option<&str> { + self.options + .iter() + .find(|(k, _)| *k == key) + .map(|(_, v)| v.as_ref()) + } + + fn stdin(&self, cmd: &mut Command, stdout: Option<&Path>) -> io::Result<()> { + asset::run_with_source(cmd, self.dir, self.name, self.scratch, self.source, stdout) + } +} + +fn blockdiag_family(job: &Job<'_>) -> io::Result<()> { + let mut command = Command::new(job.tool); + command + .args(["-a", "-o"]) + .arg(job.output) + .arg(format!("-T{}", job.format.extension())); + if let Some(font) = job.option("fontpath") { + command.arg(format!("-f{font}")); + } + job.stdin(command.arg("-"), None) +} + +/// Render `blockdiag` diagrams using `blockdiag`. +pub const BLOCKDIAG: Renderer = Renderer { + name: "blockdiag", + tool: "blockdiag", + formats: &[Format::Png, Format::Pdf, Format::Svg], + attributes: &["fontpath"], + generate: blockdiag_family, +}; + +/// Render `seqdiag` diagrams using `seqdiag`. +pub const SEQDIAG: Renderer = Renderer { + name: "seqdiag", + tool: "seqdiag", + formats: &[Format::Png, Format::Pdf, Format::Svg], + attributes: &["fontpath"], + generate: blockdiag_family, +}; + +/// Render `actdiag` diagrams using `actdiag`. +pub const ACTDIAG: Renderer = Renderer { + name: "actdiag", + tool: "actdiag", + formats: &[Format::Png, Format::Pdf, Format::Svg], + attributes: &["fontpath"], + generate: blockdiag_family, +}; + +/// Render `nwdiag` diagrams using `nwdiag`. +pub const NWDIAG: Renderer = Renderer { + name: "nwdiag", + tool: "nwdiag", + formats: &[Format::Png, Format::Pdf, Format::Svg], + attributes: &["fontpath"], + generate: blockdiag_family, +}; + +/// Render `packetdiag` diagrams using `packetdiag`. +pub const PACKETDIAG: Renderer = Renderer { + name: "packetdiag", + tool: "packetdiag", + formats: &[Format::Png, Format::Pdf, Format::Svg], + attributes: &["fontpath"], + generate: blockdiag_family, +}; + +/// Render `rackdiag` diagrams using `rackdiag`. +pub const RACKDIAG: Renderer = Renderer { + name: "rackdiag", + tool: "rackdiag", + formats: &[Format::Png, Format::Pdf, Format::Svg], + attributes: &["fontpath"], + generate: blockdiag_family, +}; + +fn nomnoml(job: &Job<'_>) -> io::Result<()> { + let input = job.source_file("nomnoml")?; + job.run(Command::new(job.tool).arg(input).arg(job.output)) +} + +/// Render `nomnoml` diagrams using `nomnoml`. +pub const NOMNOML: Renderer = Renderer { + name: "nomnoml", + tool: "nomnoml", + formats: &[Format::Svg], + attributes: &[], + generate: nomnoml, +}; + +fn smcat(job: &Job<'_>) -> io::Result<()> { + let mut cmd = Command::new(job.tool); + cmd.arg("-o") + .arg(job.output) + .args(["-T", job.format.extension()]); + job.flags(&mut cmd, &[("direction", "-d"), ("engine", "-E")]); + job.stdin(cmd.arg("-"), None) +} + +/// Render `smcat` diagrams using `smcat`. +pub const SMCAT: Renderer = Renderer { + name: "smcat", + tool: "smcat", + formats: &[Format::Svg], + attributes: &["direction", "engine"], + generate: smcat, +}; + +fn dbml(job: &Job<'_>) -> io::Result<()> { + job.stdin(&mut Command::new(job.tool), Some(job.output)) +} + +/// Render `dbml` diagrams using `dbml-renderer`. +pub const DBML: Renderer = Renderer { + name: "dbml", + tool: "dbml-renderer", + formats: &[Format::Svg], + attributes: &[], + generate: dbml, +}; + +fn graphviz_py(job: &Job<'_>) -> io::Result<()> { + let mut out = std::ffi::OsString::from("-o"); + out.push(job.output); + let mut cmd = Command::new(job.tool); + cmd.arg(out).arg(format!("-T{}", job.format.extension())); + if let Some(layout) = job.option("layout") { + cmd.arg(format!("-K{layout}")); + } + job.flags(&mut cmd, &[("argument", "-a")]); + job.stdin(&mut cmd, None) +} + +/// Render `graphviz_py` diagrams using `graphviz-py`. +pub const GRAPHVIZ_PY: Renderer = Renderer { + name: "graphviz_py", + tool: "graphviz-py", + formats: &[Format::Png, Format::Pdf, Format::Svg], + attributes: &["layout", "argument"], + generate: graphviz_py, +}; + +fn d2(job: &Job<'_>) -> io::Result<()> { + let mut cmd = Command::new(job.tool); + cmd.args(["--browser", "false"]); + for flag in [ + "layout", + "theme", + "dark-theme", + "pad", + "animate-interval", + "font-regular", + "font-italic", + "font-bold", + ] { + if let Some(value) = job.option(flag) { + cmd.arg(format!("--{flag}")).arg(value); + } + } + if job.option("sketch").is_some_and(|v| v != "false") { + cmd.arg("--sketch"); + } + job.stdin(cmd.arg("-").arg(job.output), None) +} + +/// Render `d2` diagrams using `d2`. +pub const D2: Renderer = Renderer { + name: "d2", + tool: "d2", + formats: &[Format::Svg, Format::Png, Format::Pdf], + attributes: &[ + "layout", + "theme", + "dark-theme", + "pad", + "animate-interval", + "font-regular", + "font-italic", + "font-bold", + "sketch", + ], + generate: d2, +}; + +fn shaape(job: &Job<'_>) -> io::Result<()> { + job.stdin( + Command::new(job.tool) + .arg("-o") + .arg(job.output) + .args(["-t", job.format.extension(), "-"]), + None, + ) +} + +/// Render `shaape` diagrams using `shaape`. +pub const SHAAPE: Renderer = Renderer { + name: "shaape", + tool: "shaape", + formats: &[Format::Png, Format::Svg], + attributes: &[], + generate: shaape, +}; + +fn symbolator(job: &Job<'_>) -> io::Result<()> { + let mut out = std::ffi::OsString::from("-o"); + out.push(job.output); + job.stdin( + Command::new(job.tool) + .arg("-i-") + .arg(out) + .arg(format!("-f{}", job.format.extension())), + None, + ) +} + +/// Render `symbolator` diagrams using `symbolator`. +pub const SYMBOLATOR: Renderer = Renderer { + name: "symbolator", + tool: "symbolator", + formats: &[Format::Png, Format::Pdf, Format::Svg], + attributes: &[], + generate: symbolator, +}; + +fn pintora(job: &Job<'_>) -> io::Result<()> { + let path = job.source_file("pintora")?; + let mut cmd = Command::new(job.tool); + cmd.args(["render", "-i"]) + .arg(path) + .arg("-o") + .arg(job.output); + job.flags( + &mut cmd, + &[ + ("width", "-w"), + ("theme", "-t"), + ("pixel-ratio", "-p"), + ("background-color", "-b"), + ], + ); + job.run(&mut cmd) +} + +/// Render `pintora` diagrams using `pintora`. +pub const PINTORA: Renderer = Renderer { + name: "pintora", + tool: "pintora", + formats: &[Format::Png, Format::Svg], + attributes: &["width", "theme", "background-color", "pixel-ratio"], + generate: pintora, +}; + +fn a2s(job: &Job<'_>) -> io::Result<()> { + if job.format == Format::Txt { + return std::fs::write(job.output, job.source); + } + let mut cmd = Command::new(job.tool); + cmd.arg("-o").arg(job.output); + let axes = job + .option("scalex") + .zip(job.option("scaley")) + .or_else(|| job.option("scale").map(|s| (s, s))); + if let Some((x, y)) = axes { + cmd.args(["-s", &format!("{x},{y}")]); + } + if job.option("noblur") == Some("true") { + cmd.arg("-b"); + } + job.flags(&mut cmd, &[("fontfamily", "-f")]); + // a2s counts a terminating newline as an extra row of the canvas. + let source = job + .source + .strip_suffix("\r\n") + .or_else(|| job.source.strip_suffix('\n')) + .unwrap_or(job.source); + asset::run_with_source(&mut cmd, job.dir, job.name, job.scratch, source, None) +} + +/// Render `a2s` diagrams using `a2s`. +pub const A2S: Renderer = Renderer { + name: "a2s", + tool: "a2s", + formats: &[Format::Svg, Format::Txt], + attributes: &["scalex", "scaley", "scale", "noblur", "fontfamily"], + generate: a2s, +}; + +fn svgbob(job: &Job<'_>) -> io::Result<()> { + if job.format == Format::Txt { + return std::fs::write(job.output, job.source); + } + let mut cmd = Command::new(job.tool); + cmd.arg("-o").arg(job.output); + job.flags( + &mut cmd, + &[ + ("font-family", "--font-family"), + ("font-size", "--font-size"), + ("stroke-width", "--stroke-width"), + ("scale", "--scale"), + ], + ); + job.stdin(&mut cmd, None) +} + +/// Render `svgbob` diagrams using `svgbob`. +pub const SVGBOB: Renderer = Renderer { + name: "svgbob", + tool: "svgbob", + formats: &[Format::Svg, Format::Txt], + attributes: &["font-family", "font-size", "stroke-width", "scale"], + generate: svgbob, +}; + +fn syntrax(job: &Job<'_>) -> io::Result<()> { + let input = job.source_file("spec")?; + let mut cmd = Command::new(job.tool); + cmd.arg("-i").arg(input).arg("-o").arg(job.output); + job.flags( + &mut cmd, + &[ + ("heading", "--title"), + ("scale", "--scale"), + ("style-file", "--style"), + ], + ); + if job.option("transparent") == Some("true") { + cmd.arg("--transparent"); + } + job.run(&mut cmd) +} + +/// Render `syntrax` diagrams using `syntrax`. +pub const SYNTRAX: Renderer = Renderer { + name: "syntrax", + tool: "syntrax", + formats: &[Format::Png, Format::Svg], + attributes: &["heading", "scale", "transparent", "style-file"], + generate: syntrax, +}; + +fn diagrams(job: &Job<'_>) -> io::Result<()> { + // Pass paths as arguments. Let Python bind the constructor arguments so that + // multiline calls and explicitly supplied output settings work consistently. + const WRAPPER: &str = r"import inspect, sys +from diagrams import Diagram +original = Diagram.__init__ +signature = inspect.signature(original) +def configure(*args, **kwargs): + bound = signature.bind(*args, **kwargs) + bound.arguments.update(filename=sys.argv[1], outformat=sys.argv[2], show=False) + return original(*bound.args, **bound.kwargs) +Diagram.__init__ = configure +exec(compile(sys.stdin.read(), '', 'exec'), {'__name__': '__main__'}) +"; + job.stdin( + Command::new(job.tool) + .arg("-c") + .arg(WRAPPER) + .arg(job.output.with_extension("")) + .arg(job.format.extension()), + None, + ) +} + +/// Render `diagrams` diagrams using `diagrams-python`. +pub const DIAGRAMS: Renderer = Renderer { + name: "diagrams", + tool: "diagrams-python", + formats: &[Format::Png, Format::Svg, Format::Pdf], + attributes: &[], + generate: diagrams, +}; + +fn ditaa(job: &Job<'_>) -> io::Result<()> { + if job.format == Format::Txt { + return std::fs::write(job.output, job.source); + } + let path = job.source_file("ditaa")?; + let mut cmd = Command::new(job.tool); + cmd.arg(path).arg(job.output); + if job.format == Format::Svg { + cmd.arg("--svg"); + } + job.flags( + &mut cmd, + &[ + ("scale", "--scale"), + ("tabs", "--tabs"), + ("background", "--background"), + ("bullet-characters", "--bullet-characters"), + ], + ); + for (key, trigger, flag) in [ + ("antialias", "false", "--no-antialias"), + ("separation", "false", "--no-separation"), + ("shadows", "false", "--no-shadows"), + ("round-corners", "true", "--round-corners"), + ("debug", "true", "--debug"), + ("fixed-slope", "true", "--fixed-slope"), + ("transparent", "true", "--transparent"), + ] { + if job.option(key) == Some(trigger) { + cmd.arg(flag); + } + } + job.run(&mut cmd) +} + +/// Render `ditaa` diagrams using `ditaa`. +pub const DITAA: Renderer = Renderer { + name: "ditaa", + tool: "ditaa", + formats: &[Format::Png, Format::Svg, Format::Txt], + attributes: &[ + "scale", + "tabs", + "background", + "bullet-characters", + "antialias", + "separation", + "shadows", + "round-corners", + "debug", + "fixed-slope", + "transparent", + ], + generate: ditaa, +}; + +fn tape(job: &Job<'_>) -> io::Result<()> { + let input = job.source_file("tape")?; + job.run(Command::new(job.tool).arg(input).arg("-o").arg(job.output)) +} + +/// Render `tape` diagrams using `vhs`. +pub const TAPE: Renderer = Renderer { + name: "tape", + tool: "vhs", + formats: &[Format::Gif, Format::Svg], + attributes: &[], + generate: tape, +}; + +fn gnuplot(job: &Job<'_>) -> io::Result<()> { + use std::fmt::Write as _; + let mut code = format!( + "set term {}", + if job.format == Format::Txt { + "dumb" + } else { + job.format.extension() + } + ); + if let Some((w, h)) = job.option("width").zip(job.option("height")) { + let _ = write!(code, " size {w},{h}"); + } + for key in ["transparent", "crop"] { + if let Some(v) = job.option(key) { + let prefix = if v == "false" { "no" } else { "" }; + let _ = write!(code, " {prefix}{key}"); + } + } + for key in ["font", "fontscale", "background"] { + if let Some(v) = job.option(key) { + if key == "fontscale" { + let _ = write!(code, " {key} {v}"); + } else { + let _ = write!(code, " {key} \"{v}\""); + } + } + } + let _ = writeln!(code, "\n{}", job.source); + asset::run_with_source( + &mut Command::new(job.tool), + job.dir, + job.name, + job.scratch, + &code, + Some(job.output), + ) +} + +/// Render `gnuplot` diagrams using `gnuplot`. +pub const GNUPLOT: Renderer = Renderer { + name: "gnuplot", + tool: "gnuplot", + formats: &[Format::Png, Format::Svg, Format::Gif, Format::Txt], + attributes: &[ + "width", + "height", + "transparent", + "crop", + "font", + "fontscale", + "background", + ], + generate: gnuplot, +}; + +fn umlet(job: &Job<'_>) -> io::Result<()> { + let path = job.source_file("uxf")?; + let mut input = std::ffi::OsString::from("-filename="); + input.push(path); + let mut output = std::ffi::OsString::from("-output="); + output.push(job.output); + job.run( + Command::new(job.tool) + .arg("-action=convert") + .arg(format!("-format={}", job.format.extension())) + .arg(input) + .arg(output), + ) +} + +/// Render `umlet` diagrams using `umlet`. +pub const UMLET: Renderer = Renderer { + name: "umlet", + tool: "umlet", + formats: &[Format::Svg, Format::Png, Format::Pdf, Format::Gif], + attributes: &[], + generate: umlet, +}; + +fn bpmn(job: &Job<'_>) -> io::Result<()> { + let path = job.source_file("bpmn")?; + let mut cmd = Command::new(job.tool); + cmd.arg(path) + .arg("-o") + .arg(job.output) + .args(["-t", job.format.extension()]); + job.flags(&mut cmd, &[("width", "--width"), ("height", "--height")]); + job.run(&mut cmd) +} + +/// Render `bpmn` diagrams using `bpmn-js`. +pub const BPMN: Renderer = Renderer { + name: "bpmn", + tool: "bpmn-js", + formats: &[Format::Png, Format::Svg, Format::Pdf, Format::Jpeg], + attributes: &["width", "height"], + generate: bpmn, +}; + +mod mermaid; + +/// Render `mermaid` diagrams using `mmdc`. +pub const MERMAID: Renderer = Renderer { + name: "mermaid", + tool: "mmdc", + formats: &[Format::Png, Format::Svg], + attributes: &[ + "css", + "ganttconfig", + "gantt-config", + "sequenceconfig", + "sequence-config", + "width", + "height", + "theme", + "background", + "config", + "puppeteerconfig", + "puppeteer-config", + "scale", + ], + generate: mermaid::render, +}; + +mod oxdraw; + +/// Render `oxdraw` diagrams using `oxdraw`. +pub const OXDRAW: Renderer = Renderer { + name: "oxdraw", + tool: "oxdraw", + formats: &[Format::Svg, Format::Png], + attributes: &["background", "scale"], + generate: oxdraw::render, +}; + +fn lilypond(job: &Job<'_>) -> io::Result<()> { + const PAPER: &str = "\\paper{\n oddFooterMarkup=##f\n oddHeaderMarkup=##f\n bookTitleMarkup=##f\n scoreTitleMarkup=##f\n}\n"; + let source = format!("{PAPER}{}", job.source); + let mut cmd = Command::new(job.tool); + cmd.args([ + "-daux-files=#f", + "-dbackend=eps", + "-dno-gs-load-fonts", + "-dinclude-eps-fonts", + "-o", + ]) + .arg(job.output) + .args(["-f", job.format.extension(), "-dcrop=#t"]); + if let Some(resolution) = job.option("resolution") { + cmd.arg(format!("-dresolution={resolution}")); + } + if job.format == Format::Png { + cmd.arg("-dpixmap-format=pngalpha"); + } + asset::run_with_source(cmd.arg("-"), job.dir, job.name, job.scratch, &source, None)?; + let mut cropped = job.output.as_os_str().to_owned(); + cropped.push(format!(".cropped.{}", job.format.extension())); + std::fs::rename(cropped, job.output) +} + +/// Render `lilypond` diagrams using `lilypond`. +pub const LILYPOND: Renderer = Renderer { + name: "lilypond", + tool: "lilypond", + formats: &[Format::Png, Format::Pdf], + attributes: &["resolution"], + generate: lilypond, +}; + +fn erd(job: &Job<'_>) -> io::Result<()> { + let dot = job.companion("dot")?; + let graph = job.scratch.join("layout.dot"); + job.stdin( + Command::new(job.tool) + .arg("-o") + .arg(&graph) + .args(["-f", "dot"]), + None, + )?; + let graph = asset::read_text(&graph)?; + let mut target = std::ffi::OsString::from("-o"); + target.push(job.output); + asset::run_with_source( + Command::new(dot) + .arg(target) + .arg(format!("-T{}", job.format.extension())), + job.dir, + "dot", + job.scratch, + &graph, + None, + ) +} + +/// Render `erd` diagrams using `erd`. +pub const ERD: Renderer = Renderer { + name: "erd", + tool: "erd", + formats: &[Format::Png, Format::Svg], + attributes: &[], + generate: erd, +}; + +fn penrose(job: &Job<'_>) -> io::Result<()> { + let domain = job + .option("domain_file") + .ok_or_else(|| io::Error::other("penrose requires domain_file"))?; + let style = job + .option("style_file") + .ok_or_else(|| io::Error::other("penrose requires style_file"))?; + let input = job.source_file("substance")?; + let mut cmd = Command::new(job.tool); + cmd.args(["trio", "-o"]).arg(job.output); + job.flags(&mut cmd, &[("variation", "-v")]); + job.run( + cmd.args(["--path", "/", "--trio"]) + .arg(input) + .arg(job.dir.join(domain)) + .arg(job.dir.join(style)) + .arg("--"), + ) +} + +/// Render `penrose` diagrams using `roger`. +pub const PENROSE: Renderer = Renderer { + name: "penrose", + tool: "roger", + formats: &[Format::Svg], + attributes: &["domain_file", "style_file", "variation"], + generate: penrose, +}; + +mod plantuml; + +/// Render `plantuml` diagrams using `plantuml`. +pub const PLANTUML: Renderer = Renderer { + name: "plantuml", + tool: "plantuml", + formats: &[ + Format::Png, + Format::Svg, + Format::Txt, + Format::Atxt, + Format::Utxt, + ], + attributes: &[ + "theme", + "config", + "includedir", + "size-limit", + "preprocess", + "smetana", + "debug", + ], + generate: plantuml::render, +}; + +/// Render `salt` diagrams using `plantuml`. +pub const SALT: Renderer = Renderer { + name: "salt", + tool: "plantuml", + formats: &[ + Format::Png, + Format::Svg, + Format::Txt, + Format::Atxt, + Format::Utxt, + ], + attributes: &[ + "theme", + "config", + "includedir", + "size-limit", + "preprocess", + "smetana", + "debug", + ], + generate: plantuml::render, +}; + +fn vega(job: &Job<'_>) -> io::Result<()> { + let is_lite = job.language == "vegalite" + || job.source.contains("/schema/vega-lite/") + || job.option("vegalite").is_some(); + let spec = if is_lite { + let path = job.scratch.join("spec.json"); + job.stdin( + &mut Command::new(if job.language == "vegalite" { + job.tool + } else { + job.companion("vl2vg")? + }), + Some(&path), + )?; + std::borrow::Cow::Owned(asset::read_text(&path)?) + } else { + std::borrow::Cow::Borrowed(job.source) + }; + let tool = if job.format == Format::Svg { + if job.language == "vegalite" { + job.companion("vg2svg")? + } else { + job.tool + } + } else { + job.companion("vg2png")? + }; + let mut cmd = Command::new(tool); + cmd.arg("--base").arg(job.dir); + if job.format == Format::Svg { + cmd.arg("--header"); + } + asset::run_with_source( + &mut cmd, + job.dir, + job.name, + job.scratch, + &spec, + Some(job.output), + ) +} + +/// Render `vega` diagrams using `vg2svg`. +pub const VEGA: Renderer = Renderer { + name: "vega", + tool: "vg2svg", + formats: &[Format::Svg, Format::Png], + attributes: &["vegalite"], + generate: vega, +}; + +/// Render `vegalite` diagrams using `vl2vg`. +pub const VEGALITE: Renderer = Renderer { + name: "vegalite", + tool: "vl2vg", + formats: &[Format::Svg, Format::Png], + attributes: &["vegalite"], + generate: vega, +}; diff --git a/extensions/diagram/src/renderer/mermaid.rs b/extensions/diagram/src/renderer/mermaid.rs new file mode 100644 index 000000000..68541c5d2 --- /dev/null +++ b/extensions/diagram/src/renderer/mermaid.rs @@ -0,0 +1,55 @@ +use super::Job; +use crate::asset; +use std::{io, process::Command}; +pub(super) fn render(job: &Job<'_>) -> io::Result<()> { + let input = job.source_file("mmd")?; + let mut cmd = Command::new(job.tool); + cmd.arg("-i").arg(input).arg("-o").arg(job.output); + if let Some(scale) = job.option("scale") + && (scale.is_empty() || !scale.bytes().all(|b| b.is_ascii_digit())) + { + return Err(io::Error::other( + "mermaid scale must be an unsigned integer", + )); + } + job.flags( + &mut cmd, + &[ + ("css", "--cssFile"), + ("theme", "--theme"), + ("width", "--width"), + ("height", "--height"), + ("scale", "--scale"), + ], + ); + if let Some(background) = job.option("background") { + cmd.arg("--backgroundColor") + .arg(format!("#{}", background.trim_start_matches('#'))); + } + if let Some(config) = job.option("config") { + cmd.arg("--configFile").arg(config); + } else { + let mut sections = Vec::new(); + for (key, alias, name) in [ + ("ganttconfig", "gantt-config", "gantt"), + ("sequenceconfig", "sequence-config", "sequence"), + ] { + if let Some(value) = job.option(key).or_else(|| job.option(alias)) { + let fragment = asset::read_text(&job.dir.join(value))?; + sections.push(format!(r#""{name}": {fragment}"#)); + } + } + if !sections.is_empty() { + let path = job.scratch.join("config.json"); + std::fs::write(&path, format!("{{{}}}", sections.join(",")))?; + cmd.arg("--configFile").arg(path); + } + } + if let Some(path) = job + .option("puppeteerconfig") + .or_else(|| job.option("puppeteer-config")) + { + cmd.arg("--puppeteerConfigFile").arg(path); + } + job.run(cmd.env("NODE_OPTIONS", "--unhandled-rejections=strict")) +} diff --git a/extensions/diagram/src/renderer/oxdraw.rs b/extensions/diagram/src/renderer/oxdraw.rs new file mode 100644 index 000000000..650481d64 --- /dev/null +++ b/extensions/diagram/src/renderer/oxdraw.rs @@ -0,0 +1,41 @@ +use super::Job; +use crate::asset::{self, Format}; +use std::{io, process::Command}; +pub(super) fn render(job: &Job<'_>) -> io::Result<()> { + let mut cmd = Command::new(job.tool); + job.flags( + &mut cmd, + &[("background", "--background"), ("scale", "--scale")], + ); + job.stdin( + cmd.args(["--input", "-", "--output"]) + .arg(job.output) + .args(["--output-format", job.format.extension(), "--quiet"]), + None, + )?; + if job.format == Format::Svg + && let Some(scale) = job.option("scale") + { + let scale = scale.parse::().map_err(io::Error::other)?; + if !scale.is_finite() || scale < 0.0 { + return Err(io::Error::other("scale must be finite and nonnegative")); + } + let mut svg = asset::read_text(job.output)?; + let edits = { + let doc = roxmltree::Document::parse(&svg).map_err(io::Error::other)?; + let root = doc.root_element(); + root.attributes() + .filter(|a| matches!(a.name(), "width" | "height")) + .filter_map(|a| { + let value = a.value().parse::().ok()?; + Some((a.range_value(), (value * scale).trunc().to_string())) + }) + .collect::>() + }; + for (range, value) in edits.into_iter().rev() { + svg.replace_range(range, &value); + } + std::fs::write(job.output, svg)?; + } + Ok(()) +} diff --git a/extensions/diagram/src/renderer/plantuml.rs b/extensions/diagram/src/renderer/plantuml.rs new file mode 100644 index 000000000..87ddf714c --- /dev/null +++ b/extensions/diagram/src/renderer/plantuml.rs @@ -0,0 +1,87 @@ +use super::Job; +use crate::asset::{self, Format}; +use std::{io, process::Command}; +pub(super) fn render(job: &Job<'_>) -> io::Result<()> { + let tag = if job.language == "salt" { + "salt" + } else { + "uml" + }; + let wrapped; + let source = if job.source.contains("@start") && job.source.contains("@end") { + job.source + } else { + wrapped = format!("@start{tag}\n{}\n@end{tag}", job.source); + &wrapped + }; + let command = || { + let mut cmd = Command::new(job.tool); + cmd.args([ + "-pipe", + "-charset", + "UTF-8", + "-failfast2", + "-stdrpt:1", + "-filedir", + ]) + .arg(job.dir); + if let Some(config) = job.option("config") { + cmd.arg("-config").arg(job.dir.join(config)); + } + if let Some(dir) = job.option("includedir") { + let mut arg = std::ffi::OsString::from("-Dplantuml.include.path="); + arg.push(job.dir.join(dir)); + cmd.arg(arg); + } + job.flags(&mut cmd, &[("theme", "-theme")]); + cmd.env( + "PLANTUML_LIMIT_SIZE", + job.option("size-limit").unwrap_or("4096"), + ); + cmd + }; + let expanded; + let code = if job.option("preprocess") != Some("false") && source.contains(['!', '$', '%']) { + let output = job.scratch.join("expanded.puml"); + asset::run_with_source( + command().arg("-preproc"), + job.dir, + job.name, + job.scratch, + source, + Some(&output), + )?; + expanded = asset::read_text(&output)?; + &expanded + } else { + source + }; + let mut cmd = command(); + cmd.arg(match job.format { + Format::Svg => "-tsvg", + Format::Png => "-tpng", + Format::Atxt => "-ttxt", + Format::Txt | Format::Utxt => "-tutxt", + Format::Gif | Format::Jpeg | Format::Pdf => { + return Err(io::Error::other("unsupported PlantUML format")); + } + }); + if let Ok(dot) = job.companion("dot") + && job.option("smetana").is_none() + { + cmd.arg("-graphvizdot").arg(dot); + } else { + cmd.arg("-Playout=smetana"); + } + if job.option("debug").is_some() { + cmd.arg("-v"); + } + asset::run_with_source( + &mut cmd, + job.dir, + job.name, + job.scratch, + code, + Some(job.output), + ) +} diff --git a/extensions/diagram/src/tikz.rs b/extensions/diagram/src/tikz.rs new file mode 100644 index 000000000..6636c6bc1 --- /dev/null +++ b/extensions/diagram/src/tikz.rs @@ -0,0 +1,153 @@ +//! `TikZ` standalone-document adapter ported from acdc-diagram (PR #451). + +use std::{fs, io, path::Path, process::Command}; + +use acdc_parser::{DocumentAttributeValue, extensions::BlockStyle}; + +use super::{ + OutputDirectories, + asset::{self, Format}, + diagram_attribute, diagram_source, executable, image, style, +}; + +/// Register the `tikz` style for listing and literal blocks in trusted documents. +/// The caller chooses the `LuaLaTeX` executable and optionally a PDF-to-SVG +/// converter implementing the `pdf2svg INPUT OUTPUT` interface. Both run +/// in a private scratch directory. `TeX` shell escape is disabled. +/// +/// # Errors +/// Returns an error if the supplied tools or output directory cannot be resolved. +pub fn tikz<'a>( + lualatex: &Path, + pdf2svg: Option<&Path>, + output_dir: impl Into>, +) -> io::Result { + // TeX selects its format from argv[0]. Preserve the lualatex symlink name. + let engine = executable(std::path::absolute(lualatex)?)?; + let converter = pdf2svg + .map(|tool| executable(tool.canonicalize()?)) + .transpose()?; + style("TikZ", output_dir.into(), move |root, input| { + let attrs = input.document_attributes; + let args = &input.metadata.attributes; + for key in ["lualatex", "pdflatex", "pdf2svg"] { + if args.get(key).is_some() || attrs.get(key).is_some() { + return Err(format!( + "set the {key} executable when registering the TikZ style" + )); + } + } + let command = args.get_string("command"); + for value in [ + command.as_deref(), + attrs + .get("tikz-command") + .and_then(DocumentAttributeValue::text), + ] + .into_iter() + .flatten() + { + if value != "lualatex" { + return Err("TikZ supports only command=lualatex".into()); + } + } + let format = match diagram_attribute(input, "tikz", "format").as_deref() { + Some("svg") => Format::Svg, + Some("pdf") => Format::Pdf, + Some(other) => { + return Err(format!( + "unsupported TikZ format '{other}' (expected svg or pdf)" + )); + } + None if attrs + .get("backend") + .and_then(DocumentAttributeValue::text) + .is_some_and(|backend| { + backend == "pdf" || (backend.starts_with("html") && converter.is_some()) + }) => + { + Format::Svg + } + None => Format::Pdf, + }; + let svg_tool = if format == Format::Svg { + Some( + converter + .as_ref() + .ok_or("TikZ SVG output requires a configured pdf2svg executable")?, + ) + } else { + None + }; + let preamble = args.get_string("preamble").as_deref() == Some("true") + || (&input.metadata.options) + .into_iter() + .any(|opt| *opt == "preamble"); + let document = latex_document(&diagram_source(input), preamble); + let identity = [document.as_str()]; + image( + "tikz", + root, + input, + format, + identity, + false, + |scratch, output| { + fs::write(scratch.join("input.tex"), &document)?; + asset::run( + Command::new(&engine).args([ + "-no-shell-escape", + "-halt-on-error", + "-file-line-error", + "-interaction=nonstopmode", + "input.tex", + ]), + scratch, + "lualatex", + )?; + let pdf = scratch.join("input.pdf"); + if let Some(tool) = svg_tool { + Format::Pdf.validate(&pdf)?; + asset::run(Command::new(tool).arg(pdf).arg(output), scratch, "pdf2svg") + } else { + fs::rename(pdf, output) + } + }, + ) + }) +} + +fn latex_document(source: &str, has_preamble: bool) -> String { + let (mut preamble, mut body) = ("", source); + if has_preamble { + let mut offset = 0; + for line in source.split_inclusive('\n') { + if line.trim_end_matches(['\r', '\n']) == "~~~~" { + (preamble, _) = source.split_at(offset); + (_, body) = source.split_at(offset + line.len()); + break; + } + offset += line.len(); + } + } + format!( + "\\documentclass[border=2bp, tikz]{{standalone}}\n\\usepackage{{tikz}}\n{preamble}\\begin{{document}}\n\\begingroup\n\\tikzset{{every picture/.style={{scale=1}}}}\n{body}\n\\endgroup\n\\end{{document}}\n" + ) +} + +#[cfg(test)] +mod tests { + use super::latex_document; + + #[test] + fn a_preamble_requires_a_separator_on_its_own_line() { + let body = "% an inline ~~~~ stays in the picture +\\draw (0,0) -- (1,1);"; + assert_eq!(latex_document(body, true), latex_document(body, false)); + assert_eq!( + latex_document(&format!("~~~~\n{body}"), true), + latex_document(body, false) + ); + assert!(latex_document("first\n~~~~\nnext", false).contains("first\n~~~~\nnext")); + } +} diff --git a/extensions/diagram/src/wavedrom_cli.rs b/extensions/diagram/src/wavedrom_cli.rs new file mode 100644 index 000000000..9335678d9 --- /dev/null +++ b/extensions/diagram/src/wavedrom_cli.rs @@ -0,0 +1,25 @@ +//! `WaveDrom` file-to-file adapter ported from the acdc-diagram prototype (PR #451). + +use std::{fs, io, path::Path, process::Command}; + +use super::asset::Format; + +pub(super) fn render( + tool: &Path, + body: &str, + format: Format, + scratch: &Path, + output: &Path, +) -> io::Result<()> { + let input = scratch.join("input.wvd"); + fs::write(&input, body)?; + super::asset::run( + Command::new(tool) + .arg("--input") + .arg(input) + .arg(format!("--{}", format.extension())) + .arg(output), + scratch, + "renderer", + ) +} diff --git a/extensions/diagram/tests/fixtures/ace-load.adoc b/extensions/diagram/tests/fixtures/ace-load.adoc new file mode 100644 index 000000000..399897699 --- /dev/null +++ b/extensions/diagram/tests/fixtures/ace-load.adoc @@ -0,0 +1,10 @@ +[wavedrom, , svg] +.... +{reg:[ + { bits: 7, name: 0x0b, attr: ['custom-0'] }, + { bits: 5, name: 'context', attr: ['Kd','K{Xd}'] }, + { bits: 3, name: 'ace.load', attr: ['0    0    0','0    0    1'] }, + { bits: 5, name: 'Xs1' }, + { bits: 12, name: 'immed12' }, +]} +.... diff --git a/extensions/diagram/tests/fixtures/ace-state.adoc b/extensions/diagram/tests/fixtures/ace-state.adoc new file mode 100644 index 000000000..e9096ea63 --- /dev/null +++ b/extensions/diagram/tests/fixtures/ace-state.adoc @@ -0,0 +1,75 @@ +[tikz,,svg,float="center",align="center",preamble=true,command=lualatex] +.... +\usetikzlibrary{calc,trees,matrix,positioning,chains,fit,intersections} +\usetikzlibrary{arrows,shapes.arrows,shapes.geometric,shapes.multipart,shapes.symbols} +\tikzset{ + state/.style={ rectangle, draw=black, thick, minimum height=1.66em, text centered, rounded corners=3pt}, + partial state/.style={trapezium, draw=black, thick, minimum height=1.66em, text centered, rounded corners=3pt}, + error state/.style={ rectangle, double, draw=black, semithick, minimum height=1.66em, text centered, rounded corners=3pt}, + off state/.style={ circle, double, draw=black, semithick, minimum height=1.66em, text centered, rounded corners=3pt}, + branch/.style={ fill, shape=circle, minimum size=3pt, inner sep=0pt}, + cross line/.style={preaction={draw=white, -, shorten >=3pt, shorten <=3pt, line width=2pt}}, + >=latex +} +\usepackage{fontspec} +\setmainfont[UprightFont={Petrona-Light.ttf}, + BoldFont={Petrona-Medium.ttf}, + ItalicFont={Petrona-LightItalic.ttf}, + BoldItalicFont={Petrona-MediumItalic.ttf}, + ]{Petrona-Light.ttf} +~~~~ +\begin{tikzpicture}[scale=1.1] + + \node[off state] at (-1.75,0) (off) {Off\,\vphantom{g}}; + + \node[error state, text width=1.3cm] at (2,-2) (invalid) {Invalid\vphantom{g}}; + \node[error state] at (2,2) (various errors) {\scriptsize\begin{tabular}{@{}c@{}}Privilege Violation,\\Not Implemented,\\Out of Memory\end{tabular}}; + \node[error state] at (2,3.5) (authfail) {\footnotesize\begin{tabular}{@{}c@{}}Authentication\\Failure\end{tabular}}; + \node[error state, text width=1.3cm] at (2,-3.5) (expired) {Expired}; + + \node[circle,thick,draw=black] at (4.75,2.75) (configuration hub) {}; + \node[coordinate] at ($(expired.east)+(0.5,0)$) (before expired) {}; + + \node[state, thick, text width=1.3cm] at (5.5,0) (initial) {Initial\vphantom{g}}; + \node[state, thick, text width=2.9cm] at (8.5,-1.5) (algorithm defined) {Algorithm-Defined}; + \node[state, thick, text width=2.9cm] at (8.5,1.5) (success failure) {Success / Failure}; + + %%%%%%%%%%% + + \node[above=0mm of configuration hub,xshift=5mm] (ignore) {\small\textit{Configuration}}; + \node[below right=0mm and -4mm of before expired] (ignore) {\small\textit{Expiration}}; + + %%%%%%%%%%% + + \draw[-,densely dashed] (before expired) to[out=9,in=270,looseness=0.8] (initial); + \draw[-,densely dashed] (before expired) to[out=7,in=225,looseness=0.8] (algorithm defined); + \draw[-,densely dashed] (before expired) to[out=3,in=225,looseness=0.8] (success failure); + \draw[->,densely dashed] ($(before expired)+(-0.1,0)$) -- (expired); + + \draw[<->,densely dotted] (configuration hub) to[out=-40,in=90,looseness=0.8] (initial); + \draw[<->,densely dotted] (configuration hub) to[out=-20,in=125] ($(algorithm defined.north)+(-0.333,0)$); + \draw[<->,densely dotted] (configuration hub) to[out=0,in=140] ($(success failure.north)!0.5!(success failure.north west)$); + \draw[<->,densely dotted] (configuration hub) to[out=160,in=0] (authfail); + \draw[<->,densely dotted] (configuration hub) to[out=190,in=10] (various errors); + \draw[<->,densely dotted] (configuration hub) -- (invalid.north east); + \draw[<->,densely dotted] (configuration hub) to[out=270,in=10,looseness=0.6] ($(expired.east)+(0,0.1)$); + + \draw[<->] (off) to[out=-66,in=180] (invalid); + \draw[<->] (off) to[out=78,in=180,looseness=0.7] (authfail); + \draw[<->] (off) to[out=66,in=180] (various errors); + \draw[<->] (off) to[out=-78,in=180,looseness=0.7] (expired); + + \draw[->] (algorithm defined) to[out=250,in=180] ($(algorithm defined)+(0,-1)$) to[out=0,in=290] (algorithm defined); + \draw[->, cross line] (algorithm defined) -- (invalid); + \draw[->,cross line] ($(algorithm defined.north)+(-0.667,0)$) to[out=130,in=0] (various errors); + + \draw[<->,cross line] (off) -- (initial); + \draw[<->,cross line] (off) to[out=-33,in=180,looseness=0.3] (algorithm defined); + \draw[<->,cross line] (off) to[out=33,in=180,looseness=0.3] (success failure); + + \draw[->,cross line] ($(success failure.south)+(-1,0)$) to[out=225,in=10,looseness=0.8] node[near start, above, yshift=-3pt] () {*} ($(initial.east)!0.5!(initial.north east)$); + \draw[<->,cross line] ($(algorithm defined.north)+(-1,0)$) to[out=135,in=-10,looseness=0.8] ($(initial.east)!0.5!(initial.south east)$); + \draw[->,cross line] (algorithm defined) -- (success failure); + +\end{tikzpicture} +.... diff --git a/extensions/diagram/tests/tikz.rs b/extensions/diagram/tests/tikz.rs new file mode 100644 index 000000000..85463915c --- /dev/null +++ b/extensions/diagram/tests/tikz.rs @@ -0,0 +1,177 @@ +use acdc_parser::{ + CompatibilityMode, Error, Options, SafeMode, ast::BlockKind, extensions::Registry, +}; +use std::{ + env, fs, + path::{Path, PathBuf}, +}; + +const ACE: &str = include_str!("fixtures/ace-state.adoc"); +type TestResult = Result<(), Box>; + +fn registry( + engine: &Path, + converter: Option<&Path>, + root: &Path, +) -> Result> { + let mut builder = Registry::builder(); + builder.register_block_style(acdc_diagram::tikz(engine, converter, root)?)?; + Ok(builder.build()) +} + +#[test] +fn tikz_rejects_document_tool_selection_and_requires_unsafe_mode() -> TestResult { + let dir = tempfile::tempdir()?; + let dummy = dir.path().join("not-an-executable"); + fs::write(&dummy, "")?; + let registry = registry(&dummy, None, dir.path())?; + for mode in [SafeMode::Secure, SafeMode::Server, SafeMode::Safe] { + let result = registry.parse(ACE, &Options::builder().with_safe_mode(mode).build()?); + assert!( + matches!(result, Err(Error::Extension(origin, msg)) if msg.contains("unsafe mode") && origin.location.start.line == 1) + ); + } + let unsafe_opts = Options::builder() + .with_attribute("diagram-on-error", "abort") + .with_safe_mode(SafeMode::Unsafe) + .build()?; + for (prefix, message) in [ + ("[tikz,command=/other/tool]", "command=lualatex"), + (":tikz-command: xelatex\n\n[tikz]", "command=lualatex"), + (":pdf2svg: untrusted\n\n[tikz]", "registering"), + ("[tikz,,svg]", "configured pdf2svg"), + ("[tikz,,png]", "unsupported TikZ format"), + (":diagram-format:\n\n[tikz]", "unsupported TikZ format ''"), + ( + ":diagram-format: pdf\n:tikz-format:\n\n[tikz]", + "unsupported TikZ format ''", + ), + ( + ":diagram-format: png\n\n[tikz]", + "unsupported TikZ format 'png'", + ), + ( + ":diagram-format: png\n:tikz-format: svg\n\n[tikz]", + "configured pdf2svg", + ), + ] { + let result = registry.parse(&format!("{prefix}\n....\nbody\n...."), &unsafe_opts); + assert!(matches!(result, Err(Error::Extension(_, msg)) if msg.contains(message))); + } + Ok(()) +} + +#[cfg(unix)] +#[test] +fn latex_runs_with_fixed_arguments_in_scratch_and_publishes_only_on_success() -> TestResult { + use std::os::unix::fs::PermissionsExt as _; + let dir = tempfile::tempdir()?; + let engine = dir.path().join("configured engine"); + fs::write( + &engine, + r#"#!/bin/sh +set -eu +test "$*" = "-no-shell-escape -halt-on-error -file-line-error -interaction=nonstopmode input.tex" +cmp input.tex "$(dirname "$0")/expected.tex" +printf '%%PDF-1.4\n%%%%EOF\n' > input.pdf +"#, + )?; + fs::set_permissions(&engine, fs::Permissions::from_mode(0o700))?; + fs::write( + dir.path().join("expected.tex"), + concat!( + "\\documentclass[border=2bp, tikz]{standalone}\n\\usepackage{tikz}\n", + "% preamble\n\\begin{document}\n\\begingroup\n\\tikzset{every picture/.style={scale=1}}\n", + "picture body\n\n\\endgroup\n\\end{document}\n" + ), + )?; + let registry = registry(&engine, None, dir.path())?; + let options = Options::builder() + .with_attribute("diagram-on-error", "abort") + .with_safe_mode(SafeMode::Unsafe) + .build()?; + let source = "[tikz,figure,pdf,preamble=true]\n....\n% preamble\n~~~~\npicture body\n...."; + let listing = source.replace("....", "----"); + let substituted = format!( + ":header-text: preamble\n:node-text: picture body\n\n{}", + source + .replace("preamble=true]", "preamble=true,subs=attributes]") + .replace("% preamble", "% {header-text}") + .replace("picture body", "{node-text}") + ); + for input in [source, listing.as_str(), substituted.as_str()] { + let parsed = registry.parse(input, &options)?.finish()?; + assert!(parsed.document().blocks().any( + |b| matches!(b.kind(), BlockKind::Image(i) if i.source().to_string()=="figure.pdf") + )); + } + let result = registry.parse(&source.replace("picture body", "different"), &options); + assert!(matches!(result, Err(Error::Extension(_, msg)) if msg.contains("lualatex exited"))); + assert_eq!( + fs::read(dir.path().join("figure.pdf"))?, + b"%PDF-1.4\n%%EOF\n" + ); + fs::write(&engine, "#!/bin/sh\nprintf '%%PDF-1.4\\n' > input.pdf\n")?; + let result = registry.parse(source, &options); + assert!(matches!(result, Err(Error::Extension(_, msg)) if msg.contains("invalid PDF"))); + assert_eq!( + fs::read(dir.path().join("figure.pdf"))?, + b"%PDF-1.4\n%%EOF\n" + ); + Ok(()) +} + +#[test] +#[ignore = "requires LuaLaTeX, the ACE Petrona fonts, and pdf2svg"] +fn ace_state_diagram_with_real_lualatex() -> TestResult { + let engine = PathBuf::from(env::var_os("ACDC_LUALATEX").ok_or("set ACDC_LUALATEX")?); + let converter = PathBuf::from(env::var_os("ACDC_PDF2SVG").ok_or("set ACDC_PDF2SVG")?); + for mode in [CompatibilityMode::Draft, CompatibilityMode::Asciidoctor] { + let dir = tempfile::tempdir()?; + let registry = registry(&engine, Some(&converter), dir.path())?; + let options = Options::builder() + .with_safe_mode(SafeMode::Unsafe) + .with_compatibility_mode(mode) + .build()?; + for format in ["svg", "pdf"] { + let source = format!( + ":imagesdir: diagrams\n\n{}", + ACE.replacen("tikz,,svg", &format!("tikz,,{format}"), 1) + ); + let parsed = registry.parse(&source, &options)?.finish()?; + assert_eq!(parsed.warnings(), []); + let image = parsed + .document() + .blocks() + .find_map(|b| { + if let BlockKind::Image(i) = b.kind() { + Some(i) + } else { + None + } + }) + .ok_or("expected ordinary image")?; + let target = image.source().to_string(); + assert!(target.ends_with(&format!(".{format}"))); + let asset = dir.path().join("diagrams").join(target); + if format == "svg" { + let svg = fs::read_to_string(asset)?; + let doc = roxmltree::Document::parse(&svg)?; + assert!( + doc.root_element() + .has_tag_name(("http://www.w3.org/2000/svg", "svg")) + ); + assert!(doc.descendants().any(|n| n.has_tag_name("path"))); + } else { + let pdf = lopdf::Document::load(asset)?; + assert_eq!(pdf.get_pages().len(), 1); + let text = pdf.extract_text(&[1])?; + assert!( + text.contains("Initial") && text.contains("Expiration"), + "{text}" + ); + } + } + } + Ok(()) +} diff --git a/extensions/diagram/tests/wavedrom.rs b/extensions/diagram/tests/wavedrom.rs new file mode 100644 index 000000000..c8e75eb36 --- /dev/null +++ b/extensions/diagram/tests/wavedrom.rs @@ -0,0 +1,413 @@ +use std::{ + env, fs, + io::BufReader, + path::{Path, PathBuf}, +}; + +use acdc_converters_core::{ + Converter as _, Diagnostics, Options as ConverterOptions, pipeline::Pipeline, +}; +use acdc_converters_html::{Converter, HtmlVariant}; +use acdc_parser::{ + CompatibilityMode, Error, Options, SafeMode, ast::BlockKind, extensions::Registry, +}; + +type TestResult = Result<(), Box>; +const ACE: &str = include_str!("fixtures/ace-load.adoc"); + +fn registry(tool: &Path, root: &Path) -> Result> { + let mut builder = Registry::builder(); + builder.register_block_style(acdc_diagram::wavedrom(tool, root)?)?; + Ok(builder.build()) +} + +fn render_asset( + tool: &Path, + root: &Path, + mode: CompatibilityMode, + source_text: &str, + expected_html_alt: &str, +) -> Result<(PathBuf, String), Box> { + let pipeline = Pipeline::new(Converter::new_with_variant( + ConverterOptions::builder().embedded(true).build(), + Options::builder() + .with_compatibility_mode(mode) + .with_safe_mode(SafeMode::Unsafe), + HtmlVariant::Standard, + )?) + .with_extensions(registry(tool, root)?); + let parsed = pipeline.parse(&format!("Intro.\n\n:imagesdir: images\n\n{source_text}"))?; + assert!(parsed.warnings().is_empty(), "{:?}", parsed.warnings()); + let target = parsed + .document() + .blocks() + .find_map(|block| { + if let BlockKind::Image(image) = block.kind() { + Some(image.source().to_string()) + } else { + None + } + }) + .ok_or("expected an ordinary image block")?; + let mut html = Vec::new(); + let mut warnings = Vec::new(); + let source = pipeline.converter().warning_source(); + pipeline.write_to( + parsed.document(), + &mut html, + None, + None, + &mut Diagnostics::new(&source, &mut warnings), + )?; + let reference = format!("images/{target}"); + let html = String::from_utf8(html)?; + assert!(html.contains(&format!("src=\"{reference}\""))); + assert!( + html.contains(&format!("alt=\"{expected_html_alt}\"")), + "{html}" + ); + assert_eq!(warnings, []); + Ok((root.join(reference), html)) +} + +#[test] +#[ignore = "requires the real wavedrom-cli; set ACDC_WAVEDROM_CLI to its path"] +fn ace_register_diagram_with_real_wavedrom_cli() -> TestResult { + let tool = PathBuf::from(env::var_os("ACDC_WAVEDROM_CLI").ok_or("set ACDC_WAVEDROM_CLI")?); + for mode in [CompatibilityMode::Asciidoctor, CompatibilityMode::Draft] { + let output = tempfile::tempdir()?; + let (path, _) = render_asset(&tool, output.path(), mode, ACE, "Diagram")?; + let svg = fs::read_to_string(path)?; + let document = roxmltree::Document::parse(&svg)?; + let root = document.root_element(); + assert!(root.has_tag_name(("http://www.w3.org/2000/svg", "svg"))); + assert_eq!(root.attribute("viewBox"), Some("0 0 800 84")); + for label in ["ace.load", "context", "immed12", "K{Xd}"] { + assert!( + root.descendants() + .any(|node| node.is_text() && node.text() == Some(label)), + "missing {label}" + ); + } + + let png_source = ACE.replacen(", svg]", ", png]", 1); + let (path, html) = render_asset(&tool, output.path(), mode, &png_source, "Diagram")?; + assert!(html.contains(r#"width="800" height="84""#), "{html}"); + assert_eq!(path.extension().and_then(|ext| ext.to_str()), Some("png")); + let mut reader = png::Decoder::new(BufReader::new(fs::File::open(path)?)).read_info()?; + assert_eq!(reader.info().size(), (800, 84)); + let mut pixels = vec![0; reader.output_buffer_size().ok_or("no PNG raster")?]; + let frame = reader.next_frame(&mut pixels)?; + assert_eq!((frame.width, frame.height), (800, 84)); + } + Ok(()) +} + +#[test] +fn restrictive_modes_and_invalid_targets_fail_before_execution() -> TestResult { + let output = tempfile::tempdir()?; + let dummy = output.path().join("not-an-executable"); + fs::write(&dummy, "")?; + let registry = registry(&dummy, output.path())?; + for mode in [SafeMode::Safe, SafeMode::Server, SafeMode::Secure] { + let options = Options::builder().with_safe_mode(mode).build()?; + let result = registry.parse(&format!(":safe-mode-name: unsafe\n\n{ACE}"), &options); + assert!( + matches!(result, Err(Error::Extension(_, msg)) if msg.contains("requires unsafe mode")) + ); + } + let options = Options::builder() + .with_attribute("diagram-on-error", "abort") + .with_safe_mode(SafeMode::Unsafe) + .build()?; + #[cfg(unix)] + { + let outside = tempfile::tempdir()?; + std::os::unix::fs::symlink(outside.path(), output.path().join("linked"))?; + let result = registry.parse(&format!(":imagesdir: linked\n\n{ACE}"), &options); + assert!(matches!(result, Err(Error::Extension(_, msg)) if msg.contains("imagesdir"))); + let result = registry.parse(&format!(":imagesoutdir: linked\n\n{ACE}"), &options); + assert!( + matches!(result, Err(Error::Extension(_, msg)) if msg.contains("imagesoutdir") && msg.contains("real directories")) + ); + let result = registry.parse("[wavedrom,linked/chart,svg]\n....\nbody\n....", &options); + assert!( + matches!(result, Err(Error::Extension(_, msg)) if msg.contains("target") && msg.contains("real directories")) + ); + assert_eq!(fs::read_dir(outside.path())?.count(), 0); + } + for (header, fragment) in [ + ("[wavedrom,../outside,svg]", "target"), + ("[wavedrom,boards/../clock,svg]", "target"), + ("[wavedrom,/boards/clock,svg]", "target"), + ("[wavedrom,boards//clock,svg]", "target"), + ("[wavedrom,boards/,svg]", "target"), + ("[wavedrom,,pdf]", "format"), + ( + ":diagram-svg-type: unknown\n\n[wavedrom]", + "unsupported SVG type", + ), + ("[wavedrom,chart,svg,svg-type=]", "unsupported SVG type"), + (":wavedrom: other-tool\n\n[wavedrom]", "executable"), + (":imagesoutdir: ../outside\n\n[wavedrom]", "imagesoutdir"), + (":imagesoutdir: /outside\n\n[wavedrom]", "imagesoutdir"), + (":imagesdir: ../outside\n\n[wavedrom]", "imagesdir"), + ] { + let result = registry.parse(&format!("{header}\n....\nbody\n...."), &options); + assert!(matches!(result, Err(Error::Extension(_, msg)) if msg.contains(fragment))); + } + Ok(()) +} + +#[test] +fn error_policy_uses_block_renderer_and_document_attributes_in_source_order() -> TestResult { + let root = tempfile::tempdir()?; + let tool = root.path().join("unused"); + fs::write(&tool, "")?; + let registry = registry(&tool, root.path())?; + let options = Options::builder() + .with_safe_mode(SafeMode::Unsafe) + .build()?; + let block = "[wavedrom,,pdf]\n....\nbody\n...."; + let source = format!( + "{block}\n\n:diagram-on-error: abort\n:wavedrom-on-error: log\n\n{block}\n\n:wavedrom-on-error: abort\n\n[wavedrom,,pdf,on-error=log]\n....\nbody\n...." + ); + let parsed = registry.parse(&source, &options)?.finish()?; + assert_eq!(parsed.warnings().len(), 3); + assert_eq!( + parsed + .document() + .blocks() + .filter(|b| matches!(b.kind(), BlockKind::Listing(_))) + .count(), + 3 + ); + + for prefix in [":wavedrom-on-error!:", ":diagram-on-error: log"] { + let source = format!("{source}\n\n{prefix}\n\n{block}"); + let last_block_line = u32::try_from(source.lines().count() - 3)?; + assert!( + matches!(registry.parse(&source, &options), Err(Error::Extension(origin, message)) + if origin.location.start.line == last_block_line && message.contains("unsupported WaveDrom format")) + ); + } + Ok(()) +} + +#[cfg(unix)] +#[test] +fn exact_raw_body_is_passed_to_the_renderer_and_its_svg_is_published() -> TestResult { + use std::os::unix::fs::PermissionsExt as _; + + let root = tempfile::tempdir()?; + let tool = root.path().join("renderer"); + fs::write( + &tool, + r#"#!/bin/sh +set -eu +test "$1" = --input +test "$3" = --svg +cmp "$2" "$(dirname "$0")/expected.wvd" +printf '%s' 'test' > "$4" +"#, + )?; + fs::set_permissions(&tool, fs::Permissions::from_mode(0o700))?; + let (_, delimited) = ACE.split_once("....\n").ok_or("opening delimiter")?; + fs::write( + root.path().join("expected.wvd"), + delimited + .strip_suffix("....\n") + .ok_or("closing delimiter")?, + )?; + let listing = ACE.replace("\n....\n", "\n----\n"); + let nested = ACE.replacen(", ,", ",boards/rev-a/clock_signal,", 1); + let (path, _) = render_asset( + &tool, + root.path(), + CompatibilityMode::Draft, + &nested, + "clock signal", + )?; + assert_eq!( + path, + root.path().join("images/boards/rev-a/clock_signal.svg") + ); + assert!(path.is_file()); + let named = ACE.replacen(", ,", ",clock-signal_v2,", 1); + let labeled = named.replacen("svg]", "svg,alt=\"Clock & reset\"]", 1); + let decorative = ACE.replacen("svg]", "svg,alt=\"\"]", 1); + for (source, alt) in [ + (ACE, "Diagram"), + (listing.as_str(), "Diagram"), + (&named, "clock signal v2"), + (&labeled, "Clock & reset"), + (&decorative, ""), + ] { + let (path, _) = render_asset(&tool, root.path(), CompatibilityMode::Draft, source, alt)?; + let svg = fs::read_to_string(path)?; + assert!(svg.contains("test")); + } + + // A failed rerender must preserve an existing named asset. + let registry = registry(&tool, root.path())?; + let options = Options::builder() + .with_attribute("diagram-on-error", "abort") + .with_safe_mode(SafeMode::Unsafe) + .build()?; + fs::write(root.path().join("existing.svg"), "old asset")?; + let result = registry.parse("[wavedrom,existing,svg]\n....\nbad input\n....", &options); + assert!( + matches!(result, Err(Error::Extension(origin, msg)) if origin.location.start.line == 1 && msg.contains("renderer exited")) + ); + assert_eq!( + fs::read_to_string(root.path().join("existing.svg"))?, + "old asset" + ); + Ok(()) +} + +#[cfg(unix)] +#[test] +fn attribute_substitutions_use_local_values_for_renderer_input_and_asset_names() -> TestResult { + use std::{collections::HashSet, fmt::Write as _, os::unix::fs::PermissionsExt as _}; + + let dir = tempfile::tempdir()?; + let tool = dir.path().join("renderer"); + fs::write( + &tool, + r#"#!/bin/sh +set -eu +{ + printf '%s' '' + cat "$2" + printf '%s' '' +} > "$4" +"#, + )?; + fs::set_permissions(&tool, fs::Permissions::from_mode(0o700))?; + let registry = registry(&tool, dir.path())?; + let raw = r"{label} \{label} {unknown} *raw* <1>"; + let first = "Early {label} {unknown} *raw* <1>"; + let second = "Late {label} {unknown} *raw* <1>"; + let unset = "{label} {label} {unknown} *raw* <1>"; + let mut source = String::from("= Signals\n:label: Early\n\n"); + for (attribute, style) in [ + ("", "wavedrom,subs=attributes"), + (":label: Late\n\n", "wavedrom,subs=+attributes"), + ("", "wavedrom,subs=normal"), + ("", "wavedrom"), + ("", "wavedrom,subs=none"), + ("", "wavedrom,subs=-attributes"), + (":label!:\n\n", "wavedrom,subs=attributes"), + ] { + writeln!(source, "{attribute}[{style}]\n----\n{raw}\n----\n")?; + } + + for mode in [CompatibilityMode::Draft, CompatibilityMode::Asciidoctor] { + let opts = Options::builder() + .with_safe_mode(SafeMode::Unsafe) + .with_compatibility_mode(mode) + .build()?; + let result = registry.parse(&source, &opts)?.finish()?; + let targets: Vec<_> = result + .document() + .blocks() + .filter_map(|block| { + if let BlockKind::Image(image) = block.kind() { + Some(image.source().to_string()) + } else { + None + } + }) + .collect(); + assert_eq!(targets.len(), 7); + for (name, expected) in targets + .iter() + .zip([first, second, second, raw, raw, raw, unset]) + { + let svg = fs::read_to_string(dir.path().join(name))?; + assert!(svg.contains(&format!("")), "{svg}"); + } + assert_eq!(targets.iter().collect::>().len(), 4); + } + Ok(()) +} + +#[cfg(unix)] +#[test] +fn png_selection_and_failed_publication() -> TestResult { + use std::os::unix::fs::PermissionsExt as _; + + let dir = tempfile::tempdir()?; + let tool = dir.path().join("renderer"); + fs::write( + &tool, + r#"#!/bin/sh +set -eu +test "$1" = --input +test "$3" = --png +cp "$(dirname "$0")/result.png" "$4" +"#, + )?; + fs::set_permissions(&tool, fs::Permissions::from_mode(0o700))?; + + let mut png = Vec::new(); + let mut encoder = png::Encoder::new(&mut png, 6, 4); + encoder.set_color(png::ColorType::Rgb); + encoder.set_depth(png::BitDepth::Eight); + let mut writer = encoder.write_header()?; + writer.write_image_data(&[127; 6 * 4 * 3])?; + writer.finish()?; + let result = dir.path().join("result.png"); + fs::write(&result, &png)?; + for header in [ + ":diagram-format: png\n\n[wavedrom,register]", + ":diagram-format: svg\n:wavedrom-format: png\n\n[wavedrom,register]", + ":diagram-format: png\n:wavedrom-format: svg\n\n:wavedrom-format!:\n\n[wavedrom,register]", + ":wavedrom-format: png\n\n[wavedrom,register]", + ":wavedrom-format: svg\n\n[wavedrom,register,png]", + "[wavedrom,register,svg,format=png]", + ":diagram-svg-type: unknown\n\n[wavedrom,register,png]", + ] { + let source = format!("{header}\n....\nbody\n...."); + let (path, html) = render_asset( + &tool, + dir.path(), + CompatibilityMode::Draft, + &source, + "register", + )?; + assert_eq!(path, dir.path().join("images/register.png")); + assert_eq!(fs::read(path)?, png); + assert!(html.contains(r#"width="6" height="4""#), "{html}"); + } + + let (_, html) = render_asset( + &tool, + dir.path(), + CompatibilityMode::Asciidoctor, + "[wavedrom,register,png,width=50%,scale=0.5]\n....\nbody\n....", + "register", + )?; + assert!(html.contains(r#"width="50%" height="2""#), "{html}"); + + // A successful process can still produce a truncated PNG without an IEND chunk. + png.truncate(png.len() - 12); + fs::write(result, &png)?; + let original = dir.path().join("images/register.png"); + let before = fs::read(&original)?; + let registry = registry(&tool, dir.path())?; + let options = Options::builder() + .with_attribute("diagram-on-error", "abort") + .with_safe_mode(SafeMode::Unsafe) + .build()?; + let failed = registry.parse( + ":imagesdir: images\n\n[wavedrom,register,png]\n....\nbody\n....", + &options, + ); + assert!( + matches!(failed, Err(Error::Extension(origin, msg)) if origin.location.start.line == 3 && msg.contains("invalid PNG")) + ); + assert_eq!(fs::read(original)?, before); + Ok(()) +}