From c40d9ea2f07645bf7edf2ed412c6629534172f44 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 16:40:52 +0100 Subject: [PATCH 01/60] feat(diagram): render WaveDrom literal blocks as SVG images Refs SC-261 --- .github/workflows/ci.yml | 6 +- Cargo.lock | 14 ++ Cargo.toml | 2 + extensions/diagram/CHANGELOG.md | 5 + extensions/diagram/Cargo.toml | 23 +++ extensions/diagram/README.adoc | 43 +++++ extensions/diagram/src/lib.rs | 118 ++++++++++++ extensions/diagram/src/wavedrom_cli.rs | 60 +++++++ .../diagram/tests/fixtures/ace-load.adoc | 10 ++ extensions/diagram/tests/wavedrom.rs | 168 ++++++++++++++++++ 10 files changed, 447 insertions(+), 2 deletions(-) create mode 100644 extensions/diagram/CHANGELOG.md create mode 100644 extensions/diagram/Cargo.toml create mode 100644 extensions/diagram/README.adoc create mode 100644 extensions/diagram/src/lib.rs create mode 100644 extensions/diagram/src/wavedrom_cli.rs create mode 100644 extensions/diagram/tests/fixtures/ace-load.adoc create mode 100644 extensions/diagram/tests/wavedrom.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b68b2b393..239e00ef3 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 diff --git a/Cargo.lock b/Cargo.lock index f9e46c0a9..9e9b5acd5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -153,6 +153,20 @@ dependencies = [ "viuer", ] +[[package]] +name = "acdc-diagram" +version = "0.1.0" +dependencies = [ + "acdc-converters-core", + "acdc-converters-html", + "acdc-parser", + "base64 0.23.1", + "roxmltree 0.21.1", + "sha2", + "tempfile", + "wait-timeout", +] + [[package]] name = "acdc-editor-wasm" version = "0.6.0" diff --git a/Cargo.toml b/Cargo.toml index 8a727d2c6..b6547693e 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" diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md new file mode 100644 index 000000000..ad7bf2184 --- /dev/null +++ b/extensions/diagram/CHANGELOG.md @@ -0,0 +1,5 @@ +# Changelog + +## [Unreleased] + +- Applications can opt into SVG generation for `[wavedrom, ,svg]` 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..d3204d8f2 --- /dev/null +++ b/extensions/diagram/Cargo.toml @@ -0,0 +1,23 @@ +[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 +roxmltree = "0.21" +base64.workspace = true +sha2.workspace = true +tempfile.workspace = true +wait-timeout = "0.2" + +[dev-dependencies] +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..a21d9e700 --- /dev/null +++ b/extensions/diagram/README.adoc @@ -0,0 +1,43 @@ += WaveDrom diagrams for acdc + +Applications can register the `wavedrom` literal-block style in the parser registry. +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 does not yet expose this registration. + +[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...'}]} +.... +---- + +The renderer reads the preprocessed literal body before inline substitutions. +The first positional argument names the output, e.g. `[wavedrom,clock,svg]` produces `clock.svg`. +Target names accept ASCII letters, digits, hyphens, and underscores. +An empty target uses a SHA-256 digest of the body. 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. +Use local relative image directories without URI escapes, query strings, or fragments. Symlinks in the directory path, parent traversal, and `imagesoutdir` overrides are rejected. +SVG is the supported format in this port. A failed render stops parsing at the block and preserves any previous asset. + +== Verification + +The 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)' +---- diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs new file mode 100644 index 000000000..7dd5f309f --- /dev/null +++ b/extensions/diagram/src/lib.rs @@ -0,0 +1,118 @@ +//! Render explicitly registered diagram styles into ordinary acdc image blocks. + +use std::{ + fs, io, + path::{Component, Path, PathBuf}, +}; + +use acdc_parser::{ + DocumentAttributeValue, SafeMode, + extensions::{BlockBuilder, BlockStyle, RawBlockContext, RawBlockInput}, +}; +use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; +use sha2::{Digest, Sha256}; + +mod wavedrom_cli; + +/// Register the `wavedrom` literal-block style for 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 passed verbatim to the executable. +/// +/// # Errors +/// Returns an error if either path cannot be resolved or has the wrong file type. +pub fn wavedrom(tool: &Path, output_dir: &Path) -> io::Result { + let tool = tool.canonicalize()?; + let root = output_dir.canonicalize()?; + if !tool.is_file() || !root.is_dir() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "expected a WaveDrom executable and an output directory", + )); + } + Ok( + BlockStyle::raw("wavedrom", [RawBlockContext::Literal], move || { + let tool = tool.clone(); + let root = root.clone(); + move |input: RawBlockInput<'_>| render(&tool, &root, &input).map(Some) + }) + .with_positional_attributes(["target", "format"]), + ) +} + +fn render(tool: &Path, root: &Path, input: &RawBlockInput<'_>) -> Result { + let attrs = input.document_attributes; + if attrs + .get("safe-mode-name") + .and_then(DocumentAttributeValue::text) + != Some(SafeMode::Unsafe.name()) + { + return Err("WaveDrom requires unsafe mode to run the configured executable".into()); + } + 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()); + } + if let Some(format) = args.get_string("format") + && format != "svg" + { + return Err(format!( + "unsupported WaveDrom format '{format}' (expected svg)" + )); + } + if attrs.get("imagesoutdir").is_some() { + return Err("WaveDrom writes relative to the caller's output directory; imagesoutdir is unsupported".into()); + } + let target = args.get_string("target").unwrap_or_default(); + let filename = if target.is_empty() { + let digest = Sha256::digest(input.body.as_bytes()); + format!("wavedrom-{}.svg", URL_SAFE_NO_PAD.encode(digest)) + } else { + if !target + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_')) + { + return Err("WaveDrom target must use letters, digits, hyphens, or underscores".into()); + } + format!("{target}.svg") + }; + let images = attrs + .get("imagesdir") + .and_then(DocumentAttributeValue::text) + .unwrap_or_default(); + let dir = image_directory(root, images).map_err(|e| format!("WaveDrom imagesdir: {e}"))?; + wavedrom_cli::render(tool, input.body, &dir, &filename) + .map_err(|e| format!("WaveDrom: {e}"))?; + Ok(BlockBuilder::image(filename).with_default_attributes("alt=Diagram")) +} + +// The HTML image reference already includes the source-position imagesdir. +// Keep the builder target relative to it and place the asset beneath the output root. +fn image_directory(root: &Path, images: &str) -> io::Result { + let mut dir = root.to_owned(); + if images.contains([':', '\\', '#', '?', '%']) { + return Err(io::Error::other("expected a local relative directory")); + } + let path = Path::new(images); + 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( + "imagesdir must contain only real directories", + )); + } + } + Err(e) => return Err(e), + } + } + Ok(dir) +} diff --git a/extensions/diagram/src/wavedrom_cli.rs b/extensions/diagram/src/wavedrom_cli.rs new file mode 100644 index 000000000..423bf3113 --- /dev/null +++ b/extensions/diagram/src/wavedrom_cli.rs @@ -0,0 +1,60 @@ +//! `WaveDrom` file-to-file adapter ported from the acdc-diagram prototype (PR #451). + +use std::{ + fs, + io::{self, Read as _}, + path::Path, + process::{Command, Stdio}, + time::Duration, +}; + +use wait_timeout::ChildExt as _; + +const MAX_SVG_BYTES: u64 = 16 * 1024 * 1024; + +// Use the same --input/--svg protocol as the prototype. Keeping scratch +// files beside the destination makes the final rename atomic. +pub(super) fn render(tool: &Path, body: &str, dir: &Path, filename: &str) -> io::Result<()> { + let scratch = tempfile::Builder::new() + .prefix(".acdc-wavedrom-") + .tempdir_in(dir)?; + let input = scratch.path().join("input.wvd"); + let output = scratch.path().join("output.svg"); + fs::write(&input, body)?; + let mut child = Command::new(tool) + .arg("--input") + .arg(&input) + .arg("--svg") + .arg(&output) + .current_dir(scratch.path()) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .spawn()?; + let Some(status) = child.wait_timeout(Duration::from_secs(30))? else { + child.kill()?; + child.wait()?; + return Err(io::Error::new( + io::ErrorKind::TimedOut, + "renderer exceeded 30 seconds", + )); + }; + if !status.success() { + return Err(io::Error::other(format!("renderer exited with {status}"))); + } + let mut svg = String::new(); + fs::File::open(&output)? + .take(MAX_SVG_BYTES + 1) + .read_to_string(&mut svg)?; + if svg.len() as u64 > MAX_SVG_BYTES { + return Err(io::Error::other("SVG exceeds the 16 MiB limit")); + } + let document = roxmltree::Document::parse(&svg).map_err(io::Error::other)?; + if !document + .root_element() + .has_tag_name(("http://www.w3.org/2000/svg", "svg")) + { + return Err(io::Error::other("renderer output has no SVG root element")); + } + fs::rename(output, dir.join(filename)) +} 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/wavedrom.rs b/extensions/diagram/tests/wavedrom.rs new file mode 100644 index 000000000..84773ca34 --- /dev/null +++ b/extensions/diagram/tests/wavedrom.rs @@ -0,0 +1,168 @@ +use std::{ + env, fs, + 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_ace( + tool: &Path, + root: &Path, + mode: CompatibilityMode, +) -> Result> { + 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{ACE}"))?; + 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("alt=\"Diagram\""), "{html}"); + assert_eq!(warnings, []); + Ok(fs::read_to_string(root.join(reference))?) +} + +#[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 svg = render_ace(&tool, output.path(), mode)?; + 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}" + ); + } + } + 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_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"))); + assert_eq!(fs::read_dir(outside.path())?.count(), 0); + } + for (header, fragment) in [ + ("[wavedrom,../outside,svg]", "target"), + ("[wavedrom,,png]", "format"), + (":wavedrom: other-tool\n\n[wavedrom]", "executable"), + (":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(()) +} + +#[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 svg = render_ace(&tool, root.path(), CompatibilityMode::Draft)?; + assert!(svg.contains("test")); + + // A failed rerender must preserve an existing named asset. + let registry = registry(&tool, root.path())?; + let options = Options::builder() + .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(()) +} From 550491e2dc3f5191403fcc408c52e3969e44e08a Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 16:53:36 +0100 Subject: [PATCH 02/60] feat(diagram): render TikZ literal blocks with LuaLaTeX Refs SC-261 --- Cargo.lock | 2 +- extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/Cargo.toml | 2 +- extensions/diagram/README.adoc | 33 +++- extensions/diagram/src/asset.rs | 106 ++++++++++++ extensions/diagram/src/lib.rs | 110 ++++++++++--- extensions/diagram/src/tikz.rs | 142 ++++++++++++++++ extensions/diagram/src/wavedrom_cli.rs | 67 ++------ .../diagram/tests/fixtures/ace-state.adoc | 75 +++++++++ extensions/diagram/tests/tikz.rs | 154 ++++++++++++++++++ 10 files changed, 611 insertions(+), 82 deletions(-) create mode 100644 extensions/diagram/src/asset.rs create mode 100644 extensions/diagram/src/tikz.rs create mode 100644 extensions/diagram/tests/fixtures/ace-state.adoc create mode 100644 extensions/diagram/tests/tikz.rs diff --git a/Cargo.lock b/Cargo.lock index 9e9b5acd5..3a227199c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -161,10 +161,10 @@ dependencies = [ "acdc-converters-html", "acdc-parser", "base64 0.23.1", + "lopdf", "roxmltree 0.21.1", "sha2", "tempfile", - "wait-timeout", ] [[package]] diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index ad7bf2184..11e556c63 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,4 +2,6 @@ ## [Unreleased] +- 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 opt into SVG generation for `[wavedrom, ,svg]` 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 index d3204d8f2..ae034dd05 100644 --- a/extensions/diagram/Cargo.toml +++ b/extensions/diagram/Cargo.toml @@ -13,9 +13,9 @@ roxmltree = "0.21" base64.workspace = true sha2.workspace = true tempfile.workspace = true -wait-timeout = "0.2" [dev-dependencies] +lopdf.workspace = true acdc-converters-core.workspace = true acdc-converters-html.workspace = true diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index a21d9e700..93d78cefd 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -1,4 +1,6 @@ -= WaveDrom diagrams for acdc += Diagram extensions for acdc + +== WaveDrom Applications can register the `wavedrom` literal-block style in the parser registry. Supply the path to a trusted `wavedrom-cli` executable and the directory containing the converted document. @@ -31,6 +33,25 @@ The image is an ordinary acdc block. Its file is written under the output direct Use local relative image directories without URI escapes, query strings, or fragments. Symlinks in the directory path, parent traversal, and `imagesoutdir` overrides are rejected. SVG is the supported format in this port. A failed render stops parsing at the block and preserves any previous asset. +== TikZ + +Register the `tikz` literal-block style 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]` over a 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. 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. + == Verification The adapter uses the file-to-file protocol from https://github.com/nlopes/acdc/pull/451[acdc-diagram]. @@ -41,3 +62,13 @@ It was verified with `wavedrom-cli` 3.2.0. To run the real-renderer test: ---- 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)' +---- diff --git a/extensions/diagram/src/asset.rs b/extensions/diagram/src/asset.rs new file mode 100644 index 000000000..8387ce961 --- /dev/null +++ b/extensions/diagram/src/asset.rs @@ -0,0 +1,106 @@ +use std::{ + fs, + io::{self, Read as _, Seek as _}, + path::Path, + process::{Command, Stdio}, + time::{Duration, Instant}, +}; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum Format { + Svg, + Pdf, +} + +impl Format { + pub(super) fn extension(self) -> &'static str { + match self { + Self::Svg => "svg", + Self::Pdf => "pdf", + } + } + + pub(super) fn validate(self, path: &Path) -> io::Result<()> { + const MAX_BYTES: u64 = 16 * 1024 * 1024; + 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::Svg => { + let mut svg = String::new(); + file.take(MAX_BYTES + 1).read_to_string(&mut svg)?; + if svg.len() as u64 > MAX_BYTES + || !roxmltree::Document::parse(&svg) + .map_err(io::Error::other)? + .root_element() + .has_tag_name(("http://www.w3.org/2000/svg", "svg")) + { + return Err(io::Error::other("invalid SVG output")); + } + } + 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(()) + } +} + +pub(super) fn publish( + dir: &Path, + filename: &str, + format: Format, + generate: impl FnOnce(&Path, &Path) -> io::Result<()>, +) -> io::Result<()> { + let scratch = tempfile::Builder::new() + .prefix(".acdc-diagram-") + .tempdir_in(dir)?; + let output = scratch + .path() + .join(format!("output.{}", format.extension())); + generate(scratch.path(), &output)?; + format.validate(&output)?; + fs::rename(output, dir.join(filename)) +} + +pub(super) fn run(command: &mut Command, dir: &Path, tool: &str) -> io::Result<()> { + let mut child = command + .current_dir(dir) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .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) => {} + } + 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) +} diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs index 7dd5f309f..9fb9468fa 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -12,8 +12,13 @@ use acdc_parser::{ use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; use sha2::{Digest, Sha256}; +mod asset; +mod tikz; mod wavedrom_cli; +use asset::Format; +pub use tikz::tikz; + /// Register the `wavedrom` literal-block style for 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 @@ -22,33 +27,63 @@ mod wavedrom_cli; /// # Errors /// Returns an error if either path cannot be resolved or has the wrong file type. pub fn wavedrom(tool: &Path, output_dir: &Path) -> io::Result { - let tool = tool.canonicalize()?; + let tool = executable(tool.canonicalize()?)?; + style("WaveDrom", output_dir, 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) +} + +fn style(label: &'static str, output_dir: &Path, render: F) -> io::Result +where + F: Fn(&Path, &RawBlockInput<'_>) -> Result + + Clone + + Send + + Sync + + 'static, +{ let root = output_dir.canonicalize()?; - if !tool.is_file() || !root.is_dir() { + if !root.is_dir() { return Err(io::Error::new( io::ErrorKind::InvalidInput, - "expected a WaveDrom executable and an output directory", + "expected an output directory", )); } - Ok( - BlockStyle::raw("wavedrom", [RawBlockContext::Literal], move || { - let tool = tool.clone(); + Ok(BlockStyle::raw( + label.to_ascii_lowercase(), + [RawBlockContext::Literal], + move || { let root = root.clone(); - move |input: RawBlockInput<'_>| render(&tool, &root, &input).map(Some) - }) - .with_positional_attributes(["target", "format"]), + let render = render.clone(); + move |input: RawBlockInput<'_>| { + if input + .document_attributes + .get("safe-mode-name") + .and_then(DocumentAttributeValue::text) + != Some(SafeMode::Unsafe.name()) + { + return Err(format!( + "{label} requires unsafe mode to run the configured executable" + )); + } + render(&root, &input).map(Some) + } + }, ) + .with_positional_attributes(["target", "format"])) } fn render(tool: &Path, root: &Path, input: &RawBlockInput<'_>) -> Result { let attrs = input.document_attributes; - if attrs - .get("safe-mode-name") - .and_then(DocumentAttributeValue::text) - != Some(SafeMode::Unsafe.name()) - { - return Err("WaveDrom requires unsafe mode to run the configured executable".into()); - } 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()); @@ -60,29 +95,56 @@ fn render(tool: &Path, root: &Path, input: &RawBlockInput<'_>) -> Result, + format: Format, + source: &str, + generate: impl FnOnce(&Path, &Path) -> io::Result<()>, +) -> Result { + let attrs = input.document_attributes; + let args = &input.metadata.attributes; if attrs.get("imagesoutdir").is_some() { - return Err("WaveDrom writes relative to the caller's output directory; imagesoutdir is unsupported".into()); + return Err(format!( + "{name} writes relative to the caller's output directory; imagesoutdir is unsupported" + )); } let target = args.get_string("target").unwrap_or_default(); let filename = if target.is_empty() { - let digest = Sha256::digest(input.body.as_bytes()); - format!("wavedrom-{}.svg", URL_SAFE_NO_PAD.encode(digest)) + let digest = Sha256::digest(source.as_bytes()); + format!( + "{name}-{}.{}", + URL_SAFE_NO_PAD.encode(digest), + format.extension() + ) } else { if !target .bytes() .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_')) { - return Err("WaveDrom target must use letters, digits, hyphens, or underscores".into()); + return Err(format!( + "{name} target must use letters, digits, hyphens, or underscores" + )); } - format!("{target}.svg") + format!("{target}.{}", format.extension()) }; let images = attrs .get("imagesdir") .and_then(DocumentAttributeValue::text) .unwrap_or_default(); - let dir = image_directory(root, images).map_err(|e| format!("WaveDrom imagesdir: {e}"))?; - wavedrom_cli::render(tool, input.body, &dir, &filename) - .map_err(|e| format!("WaveDrom: {e}"))?; + let dir = image_directory(root, images).map_err(|e| format!("{name} imagesdir: {e}"))?; + asset::publish(&dir, &filename, format, generate).map_err(|e| format!("{name}: {e}"))?; Ok(BlockBuilder::image(filename).with_default_attributes("alt=Diagram")) } diff --git a/extensions/diagram/src/tikz.rs b/extensions/diagram/src/tikz.rs new file mode 100644 index 000000000..284ae9ecc --- /dev/null +++ b/extensions/diagram/src/tikz.rs @@ -0,0 +1,142 @@ +//! `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::{ + asset::{self, Format}, + executable, image, style, +}; + +/// Register the `tikz` literal-block style for trusted documents in unsafe mode. +/// 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(lualatex: &Path, pdf2svg: Option<&Path>, output_dir: &Path) -> 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, 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 requested = args.get_string("format"); + let format = match requested.as_deref().or_else(|| { + attrs + .get("tikz-format") + .and_then(DocumentAttributeValue::text) + }) { + Some("svg") => Format::Svg, + Some("pdf") => Format::Pdf, + Some(other) => { + return Err(format!( + "unsupported TikZ format '{other}' (expected svg or pdf)" + )); + } + None if converter.is_some() + && attrs + .get("backend") + .and_then(DocumentAttributeValue::text) + .is_some_and(|backend| backend.starts_with("html")) => + { + Format::Svg + } + None => Format::Pdf, + }; + let svg_tool = match format { + Format::Svg => Some( + converter + .as_ref() + .ok_or("TikZ SVG output requires a configured pdf2svg executable")?, + ), + Format::Pdf => None, + }; + let preamble = args.get_string("preamble").as_deref() == Some("true") + || (&input.metadata.options) + .into_iter() + .any(|opt| *opt == "preamble"); + let document = latex_document(input.body, preamble); + image("tikz", root, input, format, &document, |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 index 423bf3113..aab45395f 100644 --- a/extensions/diagram/src/wavedrom_cli.rs +++ b/extensions/diagram/src/wavedrom_cli.rs @@ -1,60 +1,17 @@ //! `WaveDrom` file-to-file adapter ported from the acdc-diagram prototype (PR #451). -use std::{ - fs, - io::{self, Read as _}, - path::Path, - process::{Command, Stdio}, - time::Duration, -}; +use std::{fs, io, path::Path, process::Command}; -use wait_timeout::ChildExt as _; - -const MAX_SVG_BYTES: u64 = 16 * 1024 * 1024; - -// Use the same --input/--svg protocol as the prototype. Keeping scratch -// files beside the destination makes the final rename atomic. -pub(super) fn render(tool: &Path, body: &str, dir: &Path, filename: &str) -> io::Result<()> { - let scratch = tempfile::Builder::new() - .prefix(".acdc-wavedrom-") - .tempdir_in(dir)?; - let input = scratch.path().join("input.wvd"); - let output = scratch.path().join("output.svg"); +pub(super) fn render(tool: &Path, body: &str, scratch: &Path, output: &Path) -> io::Result<()> { + let input = scratch.join("input.wvd"); fs::write(&input, body)?; - let mut child = Command::new(tool) - .arg("--input") - .arg(&input) - .arg("--svg") - .arg(&output) - .current_dir(scratch.path()) - .stdin(Stdio::null()) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .spawn()?; - let Some(status) = child.wait_timeout(Duration::from_secs(30))? else { - child.kill()?; - child.wait()?; - return Err(io::Error::new( - io::ErrorKind::TimedOut, - "renderer exceeded 30 seconds", - )); - }; - if !status.success() { - return Err(io::Error::other(format!("renderer exited with {status}"))); - } - let mut svg = String::new(); - fs::File::open(&output)? - .take(MAX_SVG_BYTES + 1) - .read_to_string(&mut svg)?; - if svg.len() as u64 > MAX_SVG_BYTES { - return Err(io::Error::other("SVG exceeds the 16 MiB limit")); - } - let document = roxmltree::Document::parse(&svg).map_err(io::Error::other)?; - if !document - .root_element() - .has_tag_name(("http://www.w3.org/2000/svg", "svg")) - { - return Err(io::Error::other("renderer output has no SVG root element")); - } - fs::rename(output, dir.join(filename)) + super::asset::run( + Command::new(tool) + .arg("--input") + .arg(input) + .arg("--svg") + .arg(output), + scratch, + "renderer", + ) } 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..de3a693f5 --- /dev/null +++ b/extensions/diagram/tests/tikz.rs @@ -0,0 +1,154 @@ +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_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"), + ] { + 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_safe_mode(SafeMode::Unsafe) + .build()?; + let source = "[tikz,figure,pdf,preamble=true]\n....\n% preamble\n~~~~\npicture body\n...."; + let parsed = registry.parse(source, &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(()) +} From baf6064cf4aea45cbcf96aea0132d8571d713338 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 16:57:22 +0100 Subject: [PATCH 03/60] feat(diagram): support WaveDrom PNG output Refs SC-261 --- Cargo.lock | 1 + extensions/diagram/CHANGELOG.md | 2 +- extensions/diagram/Cargo.toml | 1 + extensions/diagram/README.adoc | 4 +- extensions/diagram/src/asset.rs | 28 +++++++- extensions/diagram/src/lib.rs | 25 +++++--- extensions/diagram/src/tikz.rs | 9 +-- extensions/diagram/src/wavedrom_cli.rs | 12 +++- extensions/diagram/tests/wavedrom.rs | 88 ++++++++++++++++++++++++-- 9 files changed, 145 insertions(+), 25 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3a227199c..f3125c47a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -162,6 +162,7 @@ dependencies = [ "acdc-parser", "base64 0.23.1", "lopdf", + "png", "roxmltree 0.21.1", "sha2", "tempfile", diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 11e556c63..330807f53 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -4,4 +4,4 @@ - 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 opt into SVG generation for `[wavedrom, ,svg]` 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. +- 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 index ae034dd05..0639951d1 100644 --- a/extensions/diagram/Cargo.toml +++ b/extensions/diagram/Cargo.toml @@ -9,6 +9,7 @@ publish = false [dependencies] acdc-parser.workspace = true +png = "0.18" roxmltree = "0.21" base64.workspace = true sha2.workspace = true diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 93d78cefd..fce1fbb11 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -31,7 +31,9 @@ Target names accept ASCII letters, digits, hyphens, and underscores. An empty target uses a SHA-256 digest of the body. 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. Use local relative image directories without URI escapes, query strings, or fragments. Symlinks in the directory path, parent traversal, and `imagesoutdir` overrides are rejected. -SVG is the supported format in this port. A failed render stops parsing at the block and preserves any previous asset. +Use `[wavedrom,clock,png]` to generate `clock.png`. SVG is the default. +The block’s format takes precedence over the `wavedrom-format` document attribute in effect at the block. +A failed render stops parsing at the block and preserves any previous asset. == TikZ diff --git a/extensions/diagram/src/asset.rs b/extensions/diagram/src/asset.rs index 8387ce961..60fc6645d 100644 --- a/extensions/diagram/src/asset.rs +++ b/extensions/diagram/src/asset.rs @@ -1,6 +1,6 @@ use std::{ fs, - io::{self, Read as _, Seek as _}, + io::{self, BufReader, Read as _, Seek as _}, path::Path, process::{Command, Stdio}, time::{Duration, Instant}, @@ -9,6 +9,7 @@ use std::{ #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum Format { Svg, + Png, Pdf, } @@ -16,6 +17,7 @@ impl Format { pub(super) fn extension(self) -> &'static str { match self { Self::Svg => "svg", + Self::Png => "png", Self::Pdf => "pdf", } } @@ -42,6 +44,7 @@ impl Format { return Err(io::Error::other("invalid SVG output")); } } + Self::Png => validate_png(file)?, Self::Pdf => { let mut signature = [0; 5]; file.read_exact(&mut signature)?; @@ -57,6 +60,29 @@ impl Format { } } +// Check the raster and its end marker before publishing, without storing a full frame. +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) +} + pub(super) fn publish( dir: &Path, filename: &str, diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs index 9fb9468fa..78645ba58 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -88,20 +88,27 @@ fn render(tool: &Path, root: &Path, input: &RawBlockInput<'_>) -> Result Format::Png, + None | Some("svg") => Format::Svg, + Some(other) => { + return Err(format!( + "unsupported WaveDrom format '{other}' (expected svg or png)" + )); + } + }; image( "wavedrom", root, input, - Format::Svg, + format, input.body, - |scratch, output| wavedrom_cli::render(tool, input.body, scratch, output), + |scratch, output| wavedrom_cli::render(tool, input.body, format, scratch, output), ) } diff --git a/extensions/diagram/src/tikz.rs b/extensions/diagram/src/tikz.rs index 284ae9ecc..122aa7ea0 100644 --- a/extensions/diagram/src/tikz.rs +++ b/extensions/diagram/src/tikz.rs @@ -69,13 +69,14 @@ pub fn tikz(lualatex: &Path, pdf2svg: Option<&Path>, output_dir: &Path) -> io::R } None => Format::Pdf, }; - let svg_tool = match format { - Format::Svg => Some( + let svg_tool = if format == Format::Svg { + Some( converter .as_ref() .ok_or("TikZ SVG output requires a configured pdf2svg executable")?, - ), - Format::Pdf => None, + ) + } else { + None }; let preamble = args.get_string("preamble").as_deref() == Some("true") || (&input.metadata.options) diff --git a/extensions/diagram/src/wavedrom_cli.rs b/extensions/diagram/src/wavedrom_cli.rs index aab45395f..9335678d9 100644 --- a/extensions/diagram/src/wavedrom_cli.rs +++ b/extensions/diagram/src/wavedrom_cli.rs @@ -2,14 +2,22 @@ use std::{fs, io, path::Path, process::Command}; -pub(super) fn render(tool: &Path, body: &str, scratch: &Path, output: &Path) -> io::Result<()> { +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("--svg") + .arg(format!("--{}", format.extension())) .arg(output), scratch, "renderer", diff --git a/extensions/diagram/tests/wavedrom.rs b/extensions/diagram/tests/wavedrom.rs index 84773ca34..35859b379 100644 --- a/extensions/diagram/tests/wavedrom.rs +++ b/extensions/diagram/tests/wavedrom.rs @@ -1,5 +1,6 @@ use std::{ env, fs, + io::BufReader, path::{Path, PathBuf}, }; @@ -20,11 +21,12 @@ fn registry(tool: &Path, root: &Path) -> Result Result> { + source_text: &str, +) -> Result> { let pipeline = Pipeline::new(Converter::new_with_variant( ConverterOptions::builder().embedded(true).build(), Options::builder() @@ -33,7 +35,7 @@ fn render_ace( HtmlVariant::Standard, )?) .with_extensions(registry(tool, root)?); - let parsed = pipeline.parse(&format!("Intro.\n\n:imagesdir: images\n\n{ACE}"))?; + 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() @@ -61,7 +63,7 @@ fn render_ace( assert!(html.contains(&format!("src=\"{reference}\""))); assert!(html.contains("alt=\"Diagram\""), "{html}"); assert_eq!(warnings, []); - Ok(fs::read_to_string(root.join(reference))?) + Ok(root.join(reference)) } #[test] @@ -70,7 +72,7 @@ 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 svg = render_ace(&tool, output.path(), mode)?; + let svg = fs::read_to_string(render_asset(&tool, output.path(), mode, ACE)?)?; let document = roxmltree::Document::parse(&svg)?; let root = document.root_element(); assert!(root.has_tag_name(("http://www.w3.org/2000/svg", "svg"))); @@ -82,6 +84,15 @@ fn ace_register_diagram_with_real_wavedrom_cli() -> TestResult { "missing {label}" ); } + + let png_source = ACE.replacen(", svg]", ", png]", 1); + let path = render_asset(&tool, output.path(), mode, &png_source)?; + 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(()) } @@ -112,7 +123,7 @@ fn restrictive_modes_and_invalid_targets_fail_before_execution() -> TestResult { } for (header, fragment) in [ ("[wavedrom,../outside,svg]", "target"), - ("[wavedrom,,png]", "format"), + ("[wavedrom,,pdf]", "format"), (":wavedrom: other-tool\n\n[wavedrom]", "executable"), (":imagesdir: ../outside\n\n[wavedrom]", "imagesdir"), ] { @@ -147,7 +158,12 @@ printf '%s' 'test' > .strip_suffix("....\n") .ok_or("closing delimiter")?, )?; - let svg = render_ace(&tool, root.path(), CompatibilityMode::Draft)?; + let svg = fs::read_to_string(render_asset( + &tool, + root.path(), + CompatibilityMode::Draft, + ACE, + )?)?; assert!(svg.contains("test")); // A failed rerender must preserve an existing named asset. @@ -166,3 +182,61 @@ printf '%s' 'test' > ); 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, 1, 1); + encoder.set_color(png::ColorType::Rgb); + encoder.set_depth(png::BitDepth::Eight); + let mut writer = encoder.write_header()?; + writer.write_image_data(&[10, 20, 30])?; + writer.finish()?; + let result = dir.path().join("result.png"); + fs::write(&result, &png)?; + for header in [ + ":wavedrom-format: png\n\n[wavedrom,register]", + ":wavedrom-format: svg\n\n[wavedrom,register,png]", + "[wavedrom,register,svg,format=png]", + ] { + let source = format!("{header}\n....\nbody\n...."); + let path = render_asset(&tool, dir.path(), CompatibilityMode::Draft, &source)?; + assert_eq!(path, dir.path().join("images/register.png")); + assert_eq!(fs::read(path)?, png); + } + + // 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_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(()) +} From 7ea1458a863a8c4a8ff83563fbb345cd31a3fffc Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 17:16:43 +0100 Subject: [PATCH 04/60] feat(cli): enable explicit diagram extension activation Expose WaveDrom and TikZ through the optional diagram feature and caller-selected executables. Resolve generated assets for file, stream, and batch conversions, including embedded HTML and PDF output. --- .github/workflows/ci.yml | 4 + AGENTS.md | 1 + Cargo.lock | 1 + Cargo.toml | 1 + acdc-cli/CHANGELOG.md | 5 + acdc-cli/Cargo.toml | 2 + acdc-cli/README.adoc | 24 ++ acdc-cli/src/subcommands/convert.rs | 25 ++- .../src/subcommands/convert/extensions.rs | 168 ++++++++++++++ acdc-cli/src/subcommands/convert/selection.rs | 32 +-- acdc-cli/tests/cli.rs | 4 + acdc-cli/tests/convert/diagram.rs | 205 ++++++++++++++++++ extensions/diagram/CHANGELOG.md | 5 + extensions/diagram/README.adoc | 6 +- extensions/diagram/src/lib.rs | 90 ++++++-- extensions/diagram/src/tikz.rs | 20 +- 16 files changed, 544 insertions(+), 49 deletions(-) create mode 100644 acdc-cli/src/subcommands/convert/extensions.rs create mode 100644 acdc-cli/tests/convert/diagram.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 239e00ef3..693d14baa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -203,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..3fb1a55dd 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 WaveDrom and TikZ 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 f3125c47a..1ecf1355c 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", diff --git a/Cargo.toml b/Cargo.toml index b6547693e..edc59c1cf 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,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..cde871270 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Builds with the optional `diagram` feature can convert WaveDrom and TikZ literal + blocks with `convert --extension diagram`. Supply `--wavedrom-cli PATH` for + WaveDrom or `--lualatex PATH` for TikZ. Add `--pdf2svg PATH` for TikZ SVG. + Rendering requires unsafe mode and a caller-selected executable. + - 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..0f1a896c1 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"] # WaveDrom and TikZ; 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..9e1dd5ca1 100644 --- a/acdc-cli/README.adoc +++ b/acdc-cli/README.adoc @@ -128,6 +128,26 @@ 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. +WaveDrom accepts SVG (default) or PNG. TikZ uses LuaLaTeX for PDF and can use pdf2svg for SVG. + +[source,console] +.... +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 +.... + +Both tool sets 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. +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. +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 +535,10 @@ echo '{"contents":"= Hello","path":"test.adoc","type":"block"}' \ | no | HTML terminal previews and session/replay rendering. +| `diagram` +| no +| Makes WaveDrom and TikZ 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..ad3dcbe68 --- /dev/null +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -0,0 +1,168 @@ +use acdc_converters_core::pipeline::{ExtensionCatalog, Extensions}; +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.wavedrom_cli.is_some() || args.diagram.lualatex.is_some() { + 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 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 select( + &self, + args: &Args, + catalog: &ExtensionCatalog, + asset_base: AssetBase, + ) -> Result { + use std::collections::{HashMap, hash_map::Entry}; + if self.wavedrom_cli.is_none() && self.lualatex.is_none() { + return Err(miette::miette!( + "--extension diagram requires --wavedrom-cli PATH or --lualatex PATH" + )); + } + // 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> { + use acdc_parser::extensions::Registry; + let output = acdc_diagram::OutputDirectories::new(linked, embedded); + let mut registry = Registry::builder(); + 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))?; + } + 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)) + } +} 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..8d92716fe --- /dev/null +++ b/acdc-cli/tests/convert/diagram.rs @@ -0,0 +1,205 @@ +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 --wavedrom-cli"), + ( + 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 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(()) + } + + #[cfg(feature = "pdf")] + #[test] + fn tikz_defaults_to_an_embeddable_asset_for_pdf_output() -> 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-")); + 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/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 330807f53..83eb3b1fb 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,11 @@ ## [Unreleased] +- 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/README.adoc b/extensions/diagram/README.adoc index fce1fbb11..ab689482c 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -5,7 +5,9 @@ Applications can register the `wavedrom` literal-block style in the parser registry. 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 does not yet expose this registration. +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] ---- @@ -47,7 +49,7 @@ builder.register_block_style(acdc_diagram::tikz(&lualatex, Some(&pdf2svg), &outp Use `[tikz,figure,svg,preamble=true,command=lualatex]` over a 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. Other configurations default to PDF. +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`. diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs index 78645ba58..f17a0c90f 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -19,6 +19,28 @@ mod wavedrom_cli; use asset::Format; 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, +} + +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 } + } +} + +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` literal-block style for 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 @@ -26,9 +48,12 @@ pub use tikz::tikz; /// /// # Errors /// Returns an error if either path cannot be resolved or has the wrong file type. -pub fn wavedrom(tool: &Path, output_dir: &Path) -> io::Result { +pub fn wavedrom<'a>( + tool: &Path, + output_dir: impl Into>, +) -> io::Result { let tool = executable(tool.canonicalize()?)?; - style("WaveDrom", output_dir, move |root, input| { + style("WaveDrom", output_dir.into(), move |root, input| { render(&tool, root, input) }) } @@ -43,26 +68,39 @@ fn executable(tool: PathBuf) -> io::Result { Ok(tool) } -fn style(label: &'static str, output_dir: &Path, render: F) -> io::Result +fn style( + label: &'static str, + output_dir: OutputDirectories<'_>, + render: F, +) -> io::Result where - F: Fn(&Path, &RawBlockInput<'_>) -> Result + F: Fn(OutputDirectories<'_>, &RawBlockInput<'_>) -> Result + Clone + Send + Sync + 'static, { - let root = output_dir.canonicalize()?; - if !root.is_dir() { - return Err(io::Error::new( - io::ErrorKind::InvalidInput, - "expected an output directory", - )); - } + 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 embedded = (output_dir.embedded != output_dir.linked) + .then(|| directory(output_dir.embedded)) + .transpose()?; Ok(BlockStyle::raw( label.to_ascii_lowercase(), [RawBlockContext::Literal], move || { - let root = root.clone(); + let linked = linked.clone(); + let embedded = embedded.clone(); let render = render.clone(); move |input: RawBlockInput<'_>| { if input @@ -75,14 +113,22 @@ where "{label} requires unsafe mode to run the configured executable" )); } - render(&root, &input).map(Some) + render( + OutputDirectories::new(&linked, embedded.as_deref().unwrap_or(&linked)), + &input, + ) + .map(Some) } }, ) .with_positional_attributes(["target", "format"])) } -fn render(tool: &Path, root: &Path, input: &RawBlockInput<'_>) -> Result { +fn render( + tool: &Path, + root: OutputDirectories<'_>, + input: &RawBlockInput<'_>, +) -> Result { let attrs = input.document_attributes; let args = &input.metadata.attributes; if args.get("wavedrom").is_some() || attrs.get("wavedrom").is_some() { @@ -114,7 +160,7 @@ fn render(tool: &Path, root: &Path, input: &RawBlockInput<'_>) -> Result, input: &RawBlockInput<'_>, format: Format, source: &str, @@ -150,6 +196,20 @@ fn image( .get("imagesdir") .and_then(DocumentAttributeValue::text) .unwrap_or_default(); + let embedded = attrs + .get("backend") + .and_then(DocumentAttributeValue::text) + .is_some_and(|name| name.starts_with("html")) + && (attrs.get("data-uri").is_some() + || (format == Format::Svg + && (&input.metadata.options) + .into_iter() + .any(|opt| *opt == "inline"))); + let root = if embedded { + roots.embedded + } else { + roots.linked + }; let dir = image_directory(root, images).map_err(|e| format!("{name} imagesdir: {e}"))?; asset::publish(&dir, &filename, format, generate).map_err(|e| format!("{name}: {e}"))?; Ok(BlockBuilder::image(filename).with_default_attributes("alt=Diagram")) diff --git a/extensions/diagram/src/tikz.rs b/extensions/diagram/src/tikz.rs index 122aa7ea0..b770c4334 100644 --- a/extensions/diagram/src/tikz.rs +++ b/extensions/diagram/src/tikz.rs @@ -5,6 +5,7 @@ use std::{fs, io, path::Path, process::Command}; use acdc_parser::{DocumentAttributeValue, extensions::BlockStyle}; use super::{ + OutputDirectories, asset::{self, Format}, executable, image, style, }; @@ -16,13 +17,17 @@ use super::{ /// /// # Errors /// Returns an error if the supplied tools or output directory cannot be resolved. -pub fn tikz(lualatex: &Path, pdf2svg: Option<&Path>, output_dir: &Path) -> io::Result { +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, move |root, input| { + style("TikZ", output_dir.into(), move |root, input| { let attrs = input.document_attributes; let args = &input.metadata.attributes; for key in ["lualatex", "pdflatex", "pdf2svg"] { @@ -59,11 +64,12 @@ pub fn tikz(lualatex: &Path, pdf2svg: Option<&Path>, output_dir: &Path) -> io::R "unsupported TikZ format '{other}' (expected svg or pdf)" )); } - None if converter.is_some() - && attrs - .get("backend") - .and_then(DocumentAttributeValue::text) - .is_some_and(|backend| backend.starts_with("html")) => + None if attrs + .get("backend") + .and_then(DocumentAttributeValue::text) + .is_some_and(|backend| { + backend == "pdf" || (backend.starts_with("html") && converter.is_some()) + }) => { Format::Svg } From f06ed17af5e05761992994650641ce4a88bd62de Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 17:22:22 +0100 Subject: [PATCH 05/60] feat(diagram): render WaveDrom and TikZ listing blocks --- acdc-cli/CHANGELOG.md | 4 ++-- acdc-cli/tests/convert/diagram.rs | 15 +++++++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 8 ++++---- extensions/diagram/src/lib.rs | 4 ++-- extensions/diagram/src/tikz.rs | 2 +- extensions/diagram/tests/tikz.rs | 11 ++++++----- extensions/diagram/tests/wavedrom.rs | 17 ++++++++++------- 8 files changed, 42 insertions(+), 21 deletions(-) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index cde871270..24a872435 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,8 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -- Builds with the optional `diagram` feature can convert WaveDrom and TikZ literal - blocks with `convert --extension diagram`. Supply `--wavedrom-cli PATH` for +- 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. Rendering requires unsafe mode and a caller-selected executable. diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 8d92716fe..3ca8eb8b1 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -87,6 +87,21 @@ mod active { run_acdc_in(root, &command, stdin) } + #[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 diagram_assets_follow_files_streams_and_batches() -> TestResult { let dir = tempfile::tempdir()?; diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 83eb3b1fb..b69bd28fc 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- WaveDrom and TikZ also render listing blocks delimited by `----`. They accept the same source, attributes, and output formats as literal blocks delimited by `....`. + - 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 diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index ab689482c..ecfa89210 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -2,7 +2,7 @@ == WaveDrom -Applications can register the `wavedrom` literal-block style in the parser registry. +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. @@ -27,7 +27,7 @@ let parsed = builder.build().parse(source, &options)?.finish()?; .... ---- -The renderer reads the preprocessed literal body before inline substitutions. +The renderer reads the preprocessed block body before inline substitutions. The first positional argument names the output, e.g. `[wavedrom,clock,svg]` produces `clock.svg`. Target names accept ASCII letters, digits, hyphens, and underscores. An empty target uses a SHA-256 digest of the body. Named `target=` and `format=` take precedence. @@ -39,14 +39,14 @@ A failed render stops parsing at the block and preserves any previous asset. == TikZ -Register the `tikz` literal-block style with the application's LuaLaTeX executable, an optional pdf2svg executable, and the converted document's output directory. +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]` over a literal block to produce `figure.svg`. +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. diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs index f17a0c90f..7eca91dde 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -41,7 +41,7 @@ impl<'a, P: AsRef + ?Sized> From<&'a P> for OutputDirectories<'a> { } } -/// Register the `wavedrom` literal-block style for a trusted renderer and an +/// 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 passed verbatim to the executable. @@ -97,7 +97,7 @@ where .transpose()?; Ok(BlockStyle::raw( label.to_ascii_lowercase(), - [RawBlockContext::Literal], + [RawBlockContext::Listing, RawBlockContext::Literal], move || { let linked = linked.clone(); let embedded = embedded.clone(); diff --git a/extensions/diagram/src/tikz.rs b/extensions/diagram/src/tikz.rs index b770c4334..38509ecea 100644 --- a/extensions/diagram/src/tikz.rs +++ b/extensions/diagram/src/tikz.rs @@ -10,7 +10,7 @@ use super::{ executable, image, style, }; -/// Register the `tikz` literal-block style for trusted documents in unsafe mode. +/// 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. diff --git a/extensions/diagram/tests/tikz.rs b/extensions/diagram/tests/tikz.rs index de3a693f5..2d11c44cc 100644 --- a/extensions/diagram/tests/tikz.rs +++ b/extensions/diagram/tests/tikz.rs @@ -76,12 +76,13 @@ printf '%%PDF-1.4\n%%%%EOF\n' > input.pdf .with_safe_mode(SafeMode::Unsafe) .build()?; let source = "[tikz,figure,pdf,preamble=true]\n....\n% preamble\n~~~~\npicture body\n...."; - let parsed = registry.parse(source, &options)?.finish()?; - assert!( - parsed.document().blocks().any( + let listing = source.replace("....", "----"); + for input in [source, listing.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!( diff --git a/extensions/diagram/tests/wavedrom.rs b/extensions/diagram/tests/wavedrom.rs index 35859b379..f3b2078a5 100644 --- a/extensions/diagram/tests/wavedrom.rs +++ b/extensions/diagram/tests/wavedrom.rs @@ -158,13 +158,16 @@ printf '%s' 'test' > .strip_suffix("....\n") .ok_or("closing delimiter")?, )?; - let svg = fs::read_to_string(render_asset( - &tool, - root.path(), - CompatibilityMode::Draft, - ACE, - )?)?; - assert!(svg.contains("test")); + let listing = ACE.replace("\n....\n", "\n----\n"); + for source in [ACE, listing.as_str()] { + let svg = fs::read_to_string(render_asset( + &tool, + root.path(), + CompatibilityMode::Draft, + source, + )?)?; + assert!(svg.contains("test")); + } // A failed rerender must preserve an existing named asset. let registry = registry(&tool, root.path())?; From 62154ed2924f66894595eb715291dc286e92c2da Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 17:31:20 +0100 Subject: [PATCH 06/60] feat(diagram): honor attribute substitutions in diagram source --- acdc-cli/CHANGELOG.md | 3 +- extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 8 +++- extensions/diagram/src/lib.rs | 22 +++++++-- extensions/diagram/src/tikz.rs | 4 +- extensions/diagram/tests/tikz.rs | 9 +++- extensions/diagram/tests/wavedrom.rs | 67 ++++++++++++++++++++++++++++ 7 files changed, 105 insertions(+), 10 deletions(-) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 24a872435..60e8074aa 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -10,7 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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. - Rendering requires unsafe mode and a caller-selected executable. + Rendering requires unsafe mode and a caller-selected executable. Add + `subs=attributes` to a diagram block to expand document attributes in its source. - Statically linked converter registrations now supply the available backend names, aliases, and variants for CLI help and conversion. diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index b69bd28fc..473ed3d31 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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 `....`. - Applications can supply separate directories for linked and embedded HTML diagrams diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index ecfa89210..20bc90bef 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -27,10 +27,14 @@ let parsed = builder.build().parse(source, &options)?.finish()?; .... ---- -The renderer reads the preprocessed block body before inline substitutions. +WaveDrom and TikZ 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`. Target names accept ASCII letters, digits, hyphens, and underscores. -An empty target uses a SHA-256 digest of the body. Named `target=` and `format=` take precedence. +An empty target uses a SHA-256 digest of the source sent to the renderer. 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. Use local relative image directories without URI escapes, query strings, or fragments. Symlinks in the directory path, parent traversal, and `imagesoutdir` overrides are rejected. Use `[wavedrom,clock,png]` to generate `clock.png`. SVG is the default. diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs index 7eca91dde..8b15048eb 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -1,12 +1,13 @@ //! Render explicitly registered diagram styles into ordinary acdc image blocks. use std::{ + borrow::Cow, fs, io, path::{Component, Path, PathBuf}, }; use acdc_parser::{ - DocumentAttributeValue, SafeMode, + DocumentAttributeValue, SafeMode, Substitution, VERBATIM, extensions::{BlockBuilder, BlockStyle, RawBlockContext, RawBlockInput}, }; use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; @@ -44,7 +45,7 @@ impl<'a, P: AsRef + ?Sized> From<&'a P> for OutputDirectories<'a> { /// 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 passed verbatim to the executable. +/// [`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. @@ -124,6 +125,18 @@ where .with_positional_attributes(["target", "format"])) } +fn diagram_source<'a>(input: &RawBlockInput<'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 render( tool: &Path, root: OutputDirectories<'_>, @@ -148,13 +161,14 @@ fn render( )); } }; + let source = diagram_source(input); image( "wavedrom", root, input, format, - input.body, - |scratch, output| wavedrom_cli::render(tool, input.body, format, scratch, output), + &source, + |scratch, output| wavedrom_cli::render(tool, &source, format, scratch, output), ) } diff --git a/extensions/diagram/src/tikz.rs b/extensions/diagram/src/tikz.rs index 38509ecea..f6b9d780e 100644 --- a/extensions/diagram/src/tikz.rs +++ b/extensions/diagram/src/tikz.rs @@ -7,7 +7,7 @@ use acdc_parser::{DocumentAttributeValue, extensions::BlockStyle}; use super::{ OutputDirectories, asset::{self, Format}, - executable, image, style, + diagram_source, executable, image, style, }; /// Register the `tikz` style for listing and literal blocks in trusted documents. @@ -88,7 +88,7 @@ pub fn tikz<'a>( || (&input.metadata.options) .into_iter() .any(|opt| *opt == "preamble"); - let document = latex_document(input.body, preamble); + let document = latex_document(&diagram_source(input), preamble); image("tikz", root, input, format, &document, |scratch, output| { fs::write(scratch.join("input.tex"), &document)?; asset::run( diff --git a/extensions/diagram/tests/tikz.rs b/extensions/diagram/tests/tikz.rs index 2d11c44cc..0509bd745 100644 --- a/extensions/diagram/tests/tikz.rs +++ b/extensions/diagram/tests/tikz.rs @@ -77,7 +77,14 @@ printf '%%PDF-1.4\n%%%%EOF\n' > input.pdf .build()?; let source = "[tikz,figure,pdf,preamble=true]\n....\n% preamble\n~~~~\npicture body\n...."; let listing = source.replace("....", "----"); - for input in [source, listing.as_str()] { + 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") diff --git a/extensions/diagram/tests/wavedrom.rs b/extensions/diagram/tests/wavedrom.rs index f3b2078a5..c08619717 100644 --- a/extensions/diagram/tests/wavedrom.rs +++ b/extensions/diagram/tests/wavedrom.rs @@ -186,6 +186,73 @@ printf '%s' 'test' > 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 { From 2263bc43e956984e6a41ee10d3c597a065c2ae78 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 18:13:55 +0100 Subject: [PATCH 07/60] feat(diagram): recover failed renders with a located warning --- acdc-cli/CHANGELOG.md | 2 ++ acdc-cli/README.adoc | 2 ++ acdc-cli/tests/convert/diagram.rs | 54 ++++++++++++++++++++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 5 ++- extensions/diagram/src/lib.rs | 42 ++++++++++++++++++---- extensions/diagram/tests/tikz.rs | 2 ++ extensions/diagram/tests/wavedrom.rs | 38 ++++++++++++++++++++ 8 files changed, 140 insertions(+), 7 deletions(-) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 60e8074aa..750684b03 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -12,6 +12,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 WaveDrom or `--lualatex PATH` for TikZ. Add `--pdf2svg PATH` for TikZ SVG. 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. diff --git a/acdc-cli/README.adoc b/acdc-cli/README.adoc index 9e1dd5ca1..8d15c10fc 100644 --- a/acdc-cli/README.adoc +++ b/acdc-cli/README.adoc @@ -140,6 +140,8 @@ acdc convert --extension diagram --lualatex /opt/tex/bin/lualatex --pdf2svg /opt Both tool sets 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. diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 3ca8eb8b1..0b79604de 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -102,6 +102,60 @@ mod active { 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()?; diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 473ed3d31..894e26d49 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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 `....`. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 20bc90bef..dea390766 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -39,7 +39,10 @@ The image is an ordinary acdc block. Its file is written under the output direct Use local relative image directories without URI escapes, query strings, or fragments. Symlinks in the directory path, parent traversal, and `imagesoutdir` overrides are rejected. Use `[wavedrom,clock,png]` to generate `clock.png`. SVG is the default. The block’s format takes precedence over the `wavedrom-format` document attribute in effect at the block. -A failed render stops parsing at the block and preserves any previous asset. +If WaveDrom or TikZ 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 `wavedrom-on-error` or `tikz-on-error`, which override `diagram-on-error` in effect at the block. +Restricted safe modes still stop before running any tool. == TikZ diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs index 8b15048eb..bd7e3f9d7 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -103,7 +103,7 @@ where let linked = linked.clone(); let embedded = embedded.clone(); let render = render.clone(); - move |input: RawBlockInput<'_>| { + move |mut input: RawBlockInput<'_>| { if input .document_attributes .get("safe-mode-name") @@ -114,17 +114,47 @@ where "{label} requires unsafe mode to run the configured executable" )); } - render( - OutputDirectories::new(&linked, embedded.as_deref().unwrap_or(&linked)), - &input, - ) - .map(Some) + let roots = OutputDirectories::new(&linked, embedded.as_deref().unwrap_or(&linked)); + match render(roots, &input) { + Ok(image) => Ok(Some(image)), + Err(error) if abort_on_error(&input, label) => Err(error), + Err(error) => { + let message = format!("Failed to generate image: {error}"); + // The renderer already received its requested substitutions. + // Display that source with ordinary listing escaping. + let listing = + BlockBuilder::listing(format!("{message}\n{}", diagram_source(&input))) + .without_attribute("subs"); + input.warn(message); + Ok(Some(listing)) + } + } } }, ) .with_positional_attributes(["target", "format"])) } +fn abort_on_error(input: &RawBlockInput<'_>, 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: &RawBlockInput<'a>) -> Cow<'a, str> { if input .metadata diff --git a/extensions/diagram/tests/tikz.rs b/extensions/diagram/tests/tikz.rs index 0509bd745..e1bd1cc25 100644 --- a/extensions/diagram/tests/tikz.rs +++ b/extensions/diagram/tests/tikz.rs @@ -32,6 +32,7 @@ fn tikz_rejects_document_tool_selection_and_requires_unsafe_mode() -> TestResult ); } let unsafe_opts = Options::builder() + .with_attribute("diagram-on-error", "abort") .with_safe_mode(SafeMode::Unsafe) .build()?; for (prefix, message) in [ @@ -73,6 +74,7 @@ printf '%%PDF-1.4\n%%%%EOF\n' > input.pdf )?; 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...."; diff --git a/extensions/diagram/tests/wavedrom.rs b/extensions/diagram/tests/wavedrom.rs index c08619717..8a99bf58b 100644 --- a/extensions/diagram/tests/wavedrom.rs +++ b/extensions/diagram/tests/wavedrom.rs @@ -111,6 +111,7 @@ fn restrictive_modes_and_invalid_targets_fail_before_execution() -> TestResult { ); } let options = Options::builder() + .with_attribute("diagram-on-error", "abort") .with_safe_mode(SafeMode::Unsafe) .build()?; #[cfg(unix)] @@ -133,6 +134,41 @@ fn restrictive_modes_and_invalid_targets_fail_before_execution() -> TestResult { 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 { @@ -172,6 +208,7 @@ printf '%s' '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")?; @@ -298,6 +335,7 @@ cp "$(dirname "$0")/result.png" "$4" 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( From caff07eef66b698559a54e8fdee9ff2a47a63e17 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 18:15:28 +0100 Subject: [PATCH 08/60] feat(diagram): honor the shared diagram-format attribute --- extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 5 ++++- extensions/diagram/src/lib.rs | 20 ++++++++++++++------ extensions/diagram/src/tikz.rs | 9 ++------- extensions/diagram/tests/tikz.rs | 13 +++++++++++++ extensions/diagram/tests/wavedrom.rs | 3 +++ 6 files changed, 38 insertions(+), 14 deletions(-) diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 894e26d49..6443dd790 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -8,6 +8,8 @@ - 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 diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index dea390766..2f5d8d167 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -38,7 +38,10 @@ An empty target uses a SHA-256 digest of the source sent to the renderer. Named The image is an ordinary acdc block. Its file is written under the output directory using the `imagesdir` in effect at the block. Use local relative image directories without URI escapes, query strings, or fragments. Symlinks in the directory path, parent traversal, and `imagesoutdir` overrides are rejected. Use `[wavedrom,clock,png]` to generate `clock.png`. SVG is the default. -The block’s format takes precedence over the `wavedrom-format` document attribute in effect at the block. +Set `:diagram-format: svg` to select a common format for WaveDrom and TikZ. +A block's positional or named format overrides `wavedrom-format` or `tikz-format`, which in turn override `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 WaveDrom or TikZ 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 `wavedrom-on-error` or `tikz-on-error`, which override `diagram-on-error` in effect at the block. diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs index bd7e3f9d7..87740f998 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -167,6 +167,19 @@ fn diagram_source<'a>(input: &RawBlockInput<'a>) -> Cow<'a, str> { } } +fn requested_format<'a>( + input: &RawBlockInput<'a>, + adapter_attribute: &str, +) -> Option> { + let attrs = input.document_attributes; + input.metadata.attributes.get_string("format").or_else(|| { + attrs + .get(adapter_attribute) + .or_else(|| attrs.get("diagram-format")) + .map(|value| Cow::Borrowed(value.text().unwrap_or_default())) + }) +} + fn render( tool: &Path, root: OutputDirectories<'_>, @@ -177,12 +190,7 @@ fn render( if args.get("wavedrom").is_some() || attrs.get("wavedrom").is_some() { return Err("set the WaveDrom executable when registering the style".into()); } - let requested = args.get_string("format"); - let format = match requested.as_deref().or_else(|| { - attrs - .get("wavedrom-format") - .and_then(DocumentAttributeValue::text) - }) { + let format = match requested_format(input, "wavedrom-format").as_deref() { Some("png") => Format::Png, None | Some("svg") => Format::Svg, Some(other) => { diff --git a/extensions/diagram/src/tikz.rs b/extensions/diagram/src/tikz.rs index f6b9d780e..d1977352b 100644 --- a/extensions/diagram/src/tikz.rs +++ b/extensions/diagram/src/tikz.rs @@ -7,7 +7,7 @@ use acdc_parser::{DocumentAttributeValue, extensions::BlockStyle}; use super::{ OutputDirectories, asset::{self, Format}, - diagram_source, executable, image, style, + diagram_source, executable, image, requested_format, style, }; /// Register the `tikz` style for listing and literal blocks in trusted documents. @@ -51,12 +51,7 @@ pub fn tikz<'a>( return Err("TikZ supports only command=lualatex".into()); } } - let requested = args.get_string("format"); - let format = match requested.as_deref().or_else(|| { - attrs - .get("tikz-format") - .and_then(DocumentAttributeValue::text) - }) { + let format = match requested_format(input, "tikz-format").as_deref() { Some("svg") => Format::Svg, Some("pdf") => Format::Pdf, Some(other) => { diff --git a/extensions/diagram/tests/tikz.rs b/extensions/diagram/tests/tikz.rs index e1bd1cc25..85463915c 100644 --- a/extensions/diagram/tests/tikz.rs +++ b/extensions/diagram/tests/tikz.rs @@ -41,6 +41,19 @@ fn tikz_rejects_document_tool_selection_and_requires_unsafe_mode() -> TestResult (":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))); diff --git a/extensions/diagram/tests/wavedrom.rs b/extensions/diagram/tests/wavedrom.rs index 8a99bf58b..ed85b8580 100644 --- a/extensions/diagram/tests/wavedrom.rs +++ b/extensions/diagram/tests/wavedrom.rs @@ -318,6 +318,9 @@ cp "$(dirname "$0")/result.png" "$4" 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]", From 3b9a4e6249e627c507d2bffa3ecb08e8985373e3 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 18:22:31 +0100 Subject: [PATCH 09/60] fix(diagram): use the named image target as the default alt text --- extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 2 ++ extensions/diagram/src/lib.rs | 7 ++++++- extensions/diagram/tests/wavedrom.rs | 30 +++++++++++++++++++++++----- 4 files changed, 35 insertions(+), 6 deletions(-) diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 6443dd790..79706a369 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 2f5d8d167..d92524e25 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -34,6 +34,8 @@ Only the attribute step of a `subs` setting affects diagram source. Formatting, The first positional argument names the output, e.g. `[wavedrom,clock,svg]` produces `clock.svg`. Target names accept ASCII letters, digits, hyphens, and underscores. +WaveDrom and TikZ use the target name 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 source sent to the renderer. 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. Use local relative image directories without URI escapes, query strings, or fragments. Symlinks in the directory path, parent traversal, and `imagesoutdir` overrides are rejected. diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs index 87740f998..13ec72548 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -264,7 +264,12 @@ fn image( }; let dir = image_directory(root, images).map_err(|e| format!("{name} imagesdir: {e}"))?; asset::publish(&dir, &filename, format, generate).map_err(|e| format!("{name}: {e}"))?; - Ok(BlockBuilder::image(filename).with_default_attributes("alt=Diagram")) + let image = BlockBuilder::image(filename); + Ok(if target.is_empty() { + image.with_default_attributes("alt=Diagram") + } else { + image + }) } // The HTML image reference already includes the source-position imagesdir. diff --git a/extensions/diagram/tests/wavedrom.rs b/extensions/diagram/tests/wavedrom.rs index ed85b8580..547877d9f 100644 --- a/extensions/diagram/tests/wavedrom.rs +++ b/extensions/diagram/tests/wavedrom.rs @@ -26,6 +26,7 @@ fn render_asset( root: &Path, mode: CompatibilityMode, source_text: &str, + expected_html_alt: &str, ) -> Result> { let pipeline = Pipeline::new(Converter::new_with_variant( ConverterOptions::builder().embedded(true).build(), @@ -61,7 +62,10 @@ fn render_asset( let reference = format!("images/{target}"); let html = String::from_utf8(html)?; assert!(html.contains(&format!("src=\"{reference}\""))); - assert!(html.contains("alt=\"Diagram\""), "{html}"); + assert!( + html.contains(&format!("alt=\"{expected_html_alt}\"")), + "{html}" + ); assert_eq!(warnings, []); Ok(root.join(reference)) } @@ -72,7 +76,7 @@ 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 svg = fs::read_to_string(render_asset(&tool, output.path(), mode, ACE)?)?; + let svg = fs::read_to_string(render_asset(&tool, output.path(), mode, ACE, "Diagram")?)?; let document = roxmltree::Document::parse(&svg)?; let root = document.root_element(); assert!(root.has_tag_name(("http://www.w3.org/2000/svg", "svg"))); @@ -86,7 +90,7 @@ fn ace_register_diagram_with_real_wavedrom_cli() -> TestResult { } let png_source = ACE.replacen(", svg]", ", png]", 1); - let path = render_asset(&tool, output.path(), mode, &png_source)?; + let path = render_asset(&tool, output.path(), mode, &png_source, "Diagram")?; 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)); @@ -195,12 +199,22 @@ printf '%s' 'test' > .ok_or("closing delimiter")?, )?; let listing = ACE.replace("\n....\n", "\n----\n"); - for source in [ACE, listing.as_str()] { + 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 svg = fs::read_to_string(render_asset( &tool, root.path(), CompatibilityMode::Draft, source, + alt, )?)?; assert!(svg.contains("test")); } @@ -326,7 +340,13 @@ cp "$(dirname "$0")/result.png" "$4" "[wavedrom,register,svg,format=png]", ] { let source = format!("{header}\n....\nbody\n...."); - let path = render_asset(&tool, dir.path(), CompatibilityMode::Draft, &source)?; + let path = render_asset( + &tool, + dir.path(), + CompatibilityMode::Draft, + &source, + "register", + )?; assert_eq!(path, dir.path().join("images/register.png")); assert_eq!(fs::read(path)?, png); } From 12aae951dd8ff39b6a01f7c31f80b6ec30ba49d9 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 18:41:00 +0100 Subject: [PATCH 10/60] feat(diagram): support nested relative image targets --- extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 5 ++-- extensions/diagram/src/lib.rs | 34 +++++++++++++++------------- extensions/diagram/tests/wavedrom.rs | 21 +++++++++++++++++ 4 files changed, 44 insertions(+), 18 deletions(-) diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 79706a369..86dc50bb5 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index d92524e25..9fb9a7f3c 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -33,8 +33,9 @@ With expansion enabled, `\{signal-label}` passes a literal `{signal-label}` to t 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`. -Target names accept ASCII letters, digits, hyphens, and underscores. -WaveDrom and TikZ use the target name as the default alternative text, with hyphens and underscores displayed as spaces. +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. +WaveDrom and TikZ 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 source sent to the renderer. 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. diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs index 13ec72548..105a45d73 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -226,7 +226,7 @@ fn image( )); } let target = args.get_string("target").unwrap_or_default(); - let filename = if target.is_empty() { + let image_target = if target.is_empty() { let digest = Sha256::digest(source.as_bytes()); format!( "{name}-{}.{}", @@ -234,12 +234,14 @@ fn image( format.extension() ) } else { - if !target - .bytes() - .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_')) - { + 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 use letters, digits, hyphens, or underscores" + "{name} target must be a relative path with nonempty segments containing only ASCII letters, digits, hyphens, or underscores" )); } format!("{target}.{}", format.extension()) @@ -262,9 +264,12 @@ fn image( } else { roots.linked }; - let dir = image_directory(root, images).map_err(|e| format!("{name} imagesdir: {e}"))?; - asset::publish(&dir, &filename, format, generate).map_err(|e| format!("{name}: {e}"))?; - let image = BlockBuilder::image(filename); + let dir = + image_directory(root.to_owned(), images).map_err(|e| format!("{name} imagesdir: {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}"))?; + asset::publish(&dir, filename, format, generate).map_err(|e| format!("{name}: {e}"))?; + let image = BlockBuilder::image(image_target); Ok(if target.is_empty() { image.with_default_attributes("alt=Diagram") } else { @@ -274,12 +279,11 @@ fn image( // The HTML image reference already includes the source-position imagesdir. // Keep the builder target relative to it and place the asset beneath the output root. -fn image_directory(root: &Path, images: &str) -> io::Result { - let mut dir = root.to_owned(); - if images.contains([':', '\\', '#', '?', '%']) { +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(images); + let path = Path::new(relative); for component in path.components() { match component { Component::CurDir => continue, @@ -292,9 +296,7 @@ fn image_directory(root: &Path, images: &str) -> io::Result { Ok(()) => {} Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { if !fs::symlink_metadata(&dir)?.file_type().is_dir() { - return Err(io::Error::other( - "imagesdir must contain only real directories", - )); + return Err(io::Error::other("path must contain only real directories")); } } Err(e) => return Err(e), diff --git a/extensions/diagram/tests/wavedrom.rs b/extensions/diagram/tests/wavedrom.rs index 547877d9f..0af9903b5 100644 --- a/extensions/diagram/tests/wavedrom.rs +++ b/extensions/diagram/tests/wavedrom.rs @@ -124,10 +124,18 @@ fn restrictive_modes_and_invalid_targets_fail_before_execution() -> TestResult { 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("[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"), (":wavedrom: other-tool\n\n[wavedrom]", "executable"), (":imagesdir: ../outside\n\n[wavedrom]", "imagesdir"), @@ -199,6 +207,19 @@ printf '%s' 'test' > .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); From 664a2d315881f087486e338ff95f36eb57c9b72a Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 19:31:39 +0100 Subject: [PATCH 11/60] fix(terminal): open absolute image paths without URL encoding --- converters/terminal/CHANGELOG.md | 2 ++ converters/terminal/src/image.rs | 8 ++++++-- 2 files changed, 8 insertions(+), 2 deletions(-) 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.", ); } From 90ed75ef1a0669b42d4561c4a4af1b4bc6eeaf72 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 19:32:01 +0100 Subject: [PATCH 12/60] feat(diagram): stage generated images under imagesoutdir --- Cargo.lock | 1 + acdc-cli/CHANGELOG.md | 2 + acdc-cli/README.adoc | 1 + .../src/subcommands/convert/extensions.rs | 3 +- acdc-cli/tests/convert/diagram.rs | 50 +++++++++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/Cargo.toml | 1 + extensions/diagram/README.adoc | 5 +- extensions/diagram/src/lib.rs | 105 ++++++++++++++---- extensions/diagram/tests/wavedrom.rs | 6 + 10 files changed, 150 insertions(+), 26 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 1ecf1355c..3681b55af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -167,6 +167,7 @@ dependencies = [ "roxmltree 0.21.1", "sha2", "tempfile", + "url", ] [[package]] diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 750684b03..a1748ed6e 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/README.adoc b/acdc-cli/README.adoc index 8d15c10fc..709b32697 100644 --- a/acdc-cli/README.adoc +++ b/acdc-cli/README.adoc @@ -145,6 +145,7 @@ Use `--fail-on-warnings` to keep that output and return status 1, or `-a diagram 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). diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index ad3dcbe68..c8e8c5e82 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -139,7 +139,8 @@ impl DiagramArgs { embedded: &Path, ) -> Result> { use acdc_parser::extensions::Registry; - let output = acdc_diagram::OutputDirectories::new(linked, embedded); + let output = acdc_diagram::OutputDirectories::new(linked, embedded) + .with_imagesoutdir_base(Path::new(".")); let mut registry = Registry::builder(); if let Some(tool) = &self.wavedrom_cli { let style = acdc_diagram::wavedrom(tool, output).map_err(|e| { diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 0b79604de..193c1b837 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -207,6 +207,51 @@ mod active { 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 { @@ -252,6 +297,11 @@ printf '%s' ' { linked: &'a Path, embedded: &'a Path, + imagesoutdir_base: &'a Path, } impl<'a> OutputDirectories<'a> { @@ -32,7 +33,19 @@ impl<'a> OutputDirectories<'a> { /// are read relative to the input document. #[must_use] pub const fn new(linked: &'a Path, embedded: &'a Path) -> Self { - Self { linked, embedded } + 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 } } @@ -93,15 +106,20 @@ where } }; let linked = directory(output_dir.linked)?; - let embedded = (output_dir.embedded != output_dir.linked) - .then(|| directory(output_dir.embedded)) - .transpose()?; + 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(BlockStyle::raw( label.to_ascii_lowercase(), [RawBlockContext::Listing, RawBlockContext::Literal], move || { let linked = linked.clone(); let embedded = embedded.clone(); + let staging = staging.clone(); let render = render.clone(); move |mut input: RawBlockInput<'_>| { if input @@ -114,7 +132,8 @@ where "{label} requires unsafe mode to run the configured executable" )); } - let roots = OutputDirectories::new(&linked, embedded.as_deref().unwrap_or(&linked)); + let roots = OutputDirectories::new(&linked, embedded.as_deref().unwrap_or(&linked)) + .with_imagesoutdir_base(staging.as_deref().unwrap_or(&linked)); match render(roots, &input) { Ok(image) => Ok(Some(image)), Err(error) if abort_on_error(&input, label) => Err(error), @@ -220,11 +239,6 @@ fn image( ) -> Result { let attrs = input.document_attributes; let args = &input.metadata.attributes; - if attrs.get("imagesoutdir").is_some() { - return Err(format!( - "{name} writes relative to the caller's output directory; imagesoutdir is unsupported" - )); - } let target = args.get_string("target").unwrap_or_default(); let image_target = if target.is_empty() { let digest = Sha256::digest(source.as_bytes()); @@ -246,30 +260,51 @@ fn image( } format!("{target}.{}", format.extension()) }; - let images = attrs - .get("imagesdir") - .and_then(DocumentAttributeValue::text) - .unwrap_or_default(); - let embedded = attrs + let backend = attrs .get("backend") .and_then(DocumentAttributeValue::text) - .is_some_and(|name| name.starts_with("html")) + .unwrap_or_default(); + let embedded = backend.starts_with("html") && (attrs.get("data-uri").is_some() || (format == Format::Svg && (&input.metadata.options) .into_iter() .any(|opt| *opt == "inline"))); - let root = if embedded { - roots.embedded + let staging = attrs.get("imagesoutdir"); + let (root, attr_name, relative) = if let Some(value) = staging { + (roots.imagesoutdir_base, "imagesoutdir", value.text()) } else { - roots.linked + 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(), images).map_err(|e| format!("{name} imagesdir: {e}"))?; + 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}"))?; + 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 + }; asset::publish(&dir, filename, format, generate).map_err(|e| format!("{name}: {e}"))?; - let image = BlockBuilder::image(image_target); + let image = BlockBuilder::image(physical_target.unwrap_or(image_target)); Ok(if target.is_empty() { image.with_default_attributes("alt=Diagram") } else { @@ -277,8 +312,30 @@ fn image( }) } -// The HTML image reference already includes the source-position imagesdir. -// Keep the builder target relative to it and place the asset beneath the output root. +#[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")); diff --git a/extensions/diagram/tests/wavedrom.rs b/extensions/diagram/tests/wavedrom.rs index 0af9903b5..fd19ff8a0 100644 --- a/extensions/diagram/tests/wavedrom.rs +++ b/extensions/diagram/tests/wavedrom.rs @@ -124,6 +124,10 @@ fn restrictive_modes_and_invalid_targets_fail_before_execution() -> TestResult { 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")) @@ -138,6 +142,8 @@ fn restrictive_modes_and_invalid_targets_fail_before_execution() -> TestResult { ("[wavedrom,boards/,svg]", "target"), ("[wavedrom,,pdf]", "format"), (":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); From baf3be03b6e6c8ffe82740a962f86d4ae7ffa319 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 19:38:46 +0100 Subject: [PATCH 13/60] test(cli): cover nested diagrams and cell-local asset staging --- acdc-cli/CHANGELOG.md | 2 + acdc-cli/tests/convert/diagram.rs | 54 +++++++++++++++++++ .../convert/fixtures/nested-diagrams.adoc | 40 ++++++++++++++ 3 files changed, 96 insertions(+) create mode 100644 acdc-cli/tests/convert/fixtures/nested-diagrams.adoc diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index a1748ed6e..80c61d3b6 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -12,6 +12,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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. 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 diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 193c1b837..137ff0c2d 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -102,6 +102,60 @@ mod active { 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()?; 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..'}]} +.... From e26073b208c94db1e39d744f7a62ec39631f7b77 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 19:44:36 +0100 Subject: [PATCH 14/60] feat(diagram): use intrinsic SVG dimensions in HTML output --- Cargo.lock | 1 + acdc-cli/CHANGELOG.md | 1 + acdc-cli/tests/convert/diagram.rs | 47 ++++++++++++++++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/Cargo.toml | 1 + extensions/diagram/README.adoc | 4 +++ extensions/diagram/src/asset.rs | 59 +++++++++++++++++++++++++------ extensions/diagram/src/lib.rs | 27 +++++++++++--- 8 files changed, 127 insertions(+), 15 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3681b55af..6b8e5c6a6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -166,6 +166,7 @@ dependencies = [ "png", "roxmltree 0.21.1", "sha2", + "svgtypes", "tempfile", "url", ] diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 80c61d3b6..40cc1c064 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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. + In HTML, SVG 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 diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 137ff0c2d..ad7c7d3c9 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -87,6 +87,53 @@ mod active { run_acdc_in(root, &command, stdin) } + #[test] + fn svg_dimensions_supply_independent_html_defaults() -> 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()?; diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 9f41b1e26..0bac76668 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- HTML output uses the generated SVG’s width and height for WaveDrom and TikZ. 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`. diff --git a/extensions/diagram/Cargo.toml b/extensions/diagram/Cargo.toml index f4d67c251..93018bac3 100644 --- a/extensions/diagram/Cargo.toml +++ b/extensions/diagram/Cargo.toml @@ -13,6 +13,7 @@ png = "0.18" roxmltree = "0.21" base64.workspace = true sha2.workspace = true +svgtypes = "0.16" tempfile.workspace = true url.workspace = true diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 96ec9e070..f94c902a6 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -43,6 +43,10 @@ Set `:imagesoutdir: staging` to write diagrams under `staging` while keeping `im 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. +For HTML, SVG diagrams supply default image dimensions from their absolute width and height, or from the `viewBox` when either dimension is unavailable. +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`. SVG is the default. Set `:diagram-format: svg` to select a common format for WaveDrom and TikZ. A block's positional or named format overrides `wavedrom-format` or `tikz-format`, which in turn override `diagram-format`. diff --git a/extensions/diagram/src/asset.rs b/extensions/diagram/src/asset.rs index 60fc6645d..fa08a8679 100644 --- a/extensions/diagram/src/asset.rs +++ b/extensions/diagram/src/asset.rs @@ -6,6 +6,41 @@ use std::{ time::{Duration, Instant}, }; +use svgtypes::{Length, LengthUnit, ViewBox}; + +pub(super) struct SvgSize { + pub(super) width: f64, + pub(super) height: f64, +} + +impl SvgSize { + fn from_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 { Svg, @@ -22,7 +57,7 @@ impl Format { } } - pub(super) fn validate(self, path: &Path) -> io::Result<()> { + pub(super) fn validate(self, path: &Path) -> io::Result> { const MAX_BYTES: u64 = 16 * 1024 * 1024; let meta = fs::symlink_metadata(path)?; if !meta.is_file() || meta.len() > MAX_BYTES { @@ -35,14 +70,15 @@ impl Format { Self::Svg => { let mut svg = String::new(); file.take(MAX_BYTES + 1).read_to_string(&mut svg)?; - if svg.len() as u64 > MAX_BYTES - || !roxmltree::Document::parse(&svg) - .map_err(io::Error::other)? - .root_element() - .has_tag_name(("http://www.w3.org/2000/svg", "svg")) - { + if svg.len() as u64 > MAX_BYTES { + return Err(io::Error::other("invalid SVG output")); + } + let document = roxmltree::Document::parse(&svg).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")); } + return Ok(SvgSize::from_root(root)); } Self::Png => validate_png(file)?, Self::Pdf => { @@ -56,7 +92,7 @@ impl Format { } } } - Ok(()) + Ok(None) } } @@ -88,7 +124,7 @@ pub(super) fn publish( filename: &str, format: Format, generate: impl FnOnce(&Path, &Path) -> io::Result<()>, -) -> io::Result<()> { +) -> io::Result> { let scratch = tempfile::Builder::new() .prefix(".acdc-diagram-") .tempdir_in(dir)?; @@ -96,8 +132,9 @@ pub(super) fn publish( .path() .join(format!("output.{}", format.extension())); generate(scratch.path(), &output)?; - format.validate(&output)?; - fs::rename(output, dir.join(filename)) + 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<()> { diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs index 333c5dbca..ede924635 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -303,12 +303,31 @@ fn image( } else { None }; - asset::publish(&dir, filename, format, generate).map_err(|e| format!("{name}: {e}"))?; + let size = + asset::publish(&dir, filename, format, generate).map_err(|e| format!("{name}: {e}"))?; let image = BlockBuilder::image(physical_target.unwrap_or(image_target)); - Ok(if target.is_empty() { - image.with_default_attributes("alt=Diagram") - } else { + let mut defaults = Vec::new(); + if target.is_empty() { + defaults.push("alt=Diagram".to_owned()); + } + if backend.starts_with("html") + && let Some(size) = size + { + let scale = 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(",")) }) } From f2683c1aa557ef3a64debd77113ff1182eb2a7b8 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 19:47:26 +0100 Subject: [PATCH 15/60] feat(diagram): use WaveDrom PNG dimensions in HTML output --- acdc-cli/CHANGELOG.md | 2 +- extensions/diagram/CHANGELOG.md | 2 +- extensions/diagram/README.adoc | 1 + extensions/diagram/src/asset.rs | 25 +++++++++++-------- extensions/diagram/tests/wavedrom.rs | 37 +++++++++++++++++----------- 5 files changed, 40 insertions(+), 27 deletions(-) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 40cc1c064..a5423c56d 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -14,7 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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. - In HTML, SVG diagrams use their intrinsic dimensions by default. Set `scale=0.5` to display them at half size, or set `width` and `height` independently. + 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 diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 0bac76668..7b5cd1d34 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,7 +2,7 @@ ## [Unreleased] -- HTML output uses the generated SVG’s width and height for WaveDrom and TikZ. 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. +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index f94c902a6..444f0298b 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -44,6 +44,7 @@ Embedding reads the staged file directly. Unset the attribute with `:imagesoutdi 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. For HTML, SVG diagrams supply default image dimensions from their absolute width and height, or from the `viewBox` when either dimension is unavailable. +WaveDrom 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. diff --git a/extensions/diagram/src/asset.rs b/extensions/diagram/src/asset.rs index fa08a8679..e8d41f457 100644 --- a/extensions/diagram/src/asset.rs +++ b/extensions/diagram/src/asset.rs @@ -8,13 +8,13 @@ use std::{ use svgtypes::{Length, LengthUnit, ViewBox}; -pub(super) struct SvgSize { +pub(super) struct ImageSize { pub(super) width: f64, pub(super) height: f64, } -impl SvgSize { - fn from_root(root: roxmltree::Node<'_, '_>) -> Option { +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 { @@ -57,7 +57,7 @@ impl Format { } } - pub(super) fn validate(self, path: &Path) -> io::Result> { + pub(super) fn validate(self, path: &Path) -> io::Result> { const MAX_BYTES: u64 = 16 * 1024 * 1024; let meta = fs::symlink_metadata(path)?; if !meta.is_file() || meta.len() > MAX_BYTES { @@ -78,9 +78,9 @@ impl Format { if !root.has_tag_name(("http://www.w3.org/2000/svg", "svg")) { return Err(io::Error::other("invalid SVG output")); } - return Ok(SvgSize::from_root(root)); + Ok(ImageSize::from_svg_root(root)) } - Self::Png => validate_png(file)?, + Self::Png => validate_png(file).map(Some), Self::Pdf => { let mut signature = [0; 5]; file.read_exact(&mut signature)?; @@ -90,14 +90,14 @@ impl Format { if &signature != b"%PDF-" || !tail.trim_ascii_end().ends_with(b"%%EOF") { return Err(io::Error::other("invalid PDF output")); } + Ok(None) } } - Ok(None) } } // Check the raster and its end marker before publishing, without storing a full frame. -fn validate_png(file: fs::File) -> io::Result<()> { +fn validate_png(file: fs::File) -> io::Result { let invalid = |e: png::DecodingError| { io::Error::new( io::ErrorKind::InvalidData, @@ -116,7 +116,12 @@ fn validate_png(file: fs::File) -> io::Result<()> { )); } while reader.next_row().map_err(invalid)?.is_some() {} - reader.finish().map_err(invalid) + reader.finish().map_err(invalid)?; + let (width, height) = reader.info().size(); + Ok(ImageSize { + width: f64::from(width), + height: f64::from(height), + }) } pub(super) fn publish( @@ -124,7 +129,7 @@ pub(super) fn publish( filename: &str, format: Format, generate: impl FnOnce(&Path, &Path) -> io::Result<()>, -) -> io::Result> { +) -> io::Result> { let scratch = tempfile::Builder::new() .prefix(".acdc-diagram-") .tempdir_in(dir)?; diff --git a/extensions/diagram/tests/wavedrom.rs b/extensions/diagram/tests/wavedrom.rs index fd19ff8a0..096863320 100644 --- a/extensions/diagram/tests/wavedrom.rs +++ b/extensions/diagram/tests/wavedrom.rs @@ -27,7 +27,7 @@ fn render_asset( mode: CompatibilityMode, source_text: &str, expected_html_alt: &str, -) -> Result> { +) -> Result<(PathBuf, String), Box> { let pipeline = Pipeline::new(Converter::new_with_variant( ConverterOptions::builder().embedded(true).build(), Options::builder() @@ -67,7 +67,7 @@ fn render_asset( "{html}" ); assert_eq!(warnings, []); - Ok(root.join(reference)) + Ok((root.join(reference), html)) } #[test] @@ -76,7 +76,8 @@ 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 svg = fs::read_to_string(render_asset(&tool, output.path(), mode, ACE, "Diagram")?)?; + 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"))); @@ -90,7 +91,8 @@ fn ace_register_diagram_with_real_wavedrom_cli() -> TestResult { } let png_source = ACE.replacen(", svg]", ", png]", 1); - let path = render_asset(&tool, output.path(), mode, &png_source, "Diagram")?; + 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)); @@ -214,7 +216,7 @@ printf '%s' 'test' > )?; let listing = ACE.replace("\n....\n", "\n----\n"); let nested = ACE.replacen(", ,", ",boards/rev-a/clock_signal,", 1); - let path = render_asset( + let (path, _) = render_asset( &tool, root.path(), CompatibilityMode::Draft, @@ -236,13 +238,8 @@ printf '%s' 'test' > (&labeled, "Clock & reset"), (&decorative, ""), ] { - let svg = fs::read_to_string(render_asset( - &tool, - root.path(), - CompatibilityMode::Draft, - source, - alt, - )?)?; + let (path, _) = render_asset(&tool, root.path(), CompatibilityMode::Draft, source, alt)?; + let svg = fs::read_to_string(path)?; assert!(svg.contains("test")); } @@ -350,11 +347,11 @@ 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, 1, 1); + 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(&[10, 20, 30])?; + writer.write_image_data(&[127; 6 * 4 * 3])?; writer.finish()?; let result = dir.path().join("result.png"); fs::write(&result, &png)?; @@ -367,7 +364,7 @@ cp "$(dirname "$0")/result.png" "$4" "[wavedrom,register,svg,format=png]", ] { let source = format!("{header}\n....\nbody\n...."); - let path = render_asset( + let (path, html) = render_asset( &tool, dir.path(), CompatibilityMode::Draft, @@ -376,8 +373,18 @@ cp "$(dirname "$0")/result.png" "$4" )?; 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)?; From e50f09f109e6906c5557a289e78f9a93c53701a9 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 19:55:10 +0100 Subject: [PATCH 16/60] feat(diagram): honor SVG presentation mode attributes --- acdc-cli/CHANGELOG.md | 1 + acdc-cli/tests/convert/diagram.rs | 63 ++++++++++++++++++++++++++++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 3 ++ extensions/diagram/src/lib.rs | 55 ++++++++++++++++++------ extensions/diagram/src/tikz.rs | 4 +- extensions/diagram/tests/wavedrom.rs | 6 +++ 7 files changed, 120 insertions(+), 14 deletions(-) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index a5423c56d..e84cde4bc 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 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. diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index ad7c7d3c9..415ec8669 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -87,6 +87,69 @@ mod active { run_acdc_in(root, &command, stdin) } + #[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()?; diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 7b5cd1d34..bead52238 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 444f0298b..73789ac37 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -43,6 +43,9 @@ Set `:imagesoutdir: staging` to write diagrams under `staging` while keeping `im 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 ``. +The `wavedrom-svg-type` and `tikz-svg-type` attributes override the shared setting. Each block can override either 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. WaveDrom 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. diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs index ede924635..aa9af7c29 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -186,15 +186,16 @@ fn diagram_source<'a>(input: &RawBlockInput<'a>) -> Cow<'a, str> { } } -fn requested_format<'a>( +fn diagram_attribute<'a>( input: &RawBlockInput<'a>, - adapter_attribute: &str, + renderer: &str, + key: &str, ) -> Option> { let attrs = input.document_attributes; - input.metadata.attributes.get_string("format").or_else(|| { + input.metadata.attributes.get_string(key).or_else(|| { attrs - .get(adapter_attribute) - .or_else(|| attrs.get("diagram-format")) + .get(&format!("{renderer}-{key}")) + .or_else(|| attrs.get(&format!("diagram-{key}"))) .map(|value| Cow::Borrowed(value.text().unwrap_or_default())) }) } @@ -209,7 +210,7 @@ fn render( 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 requested_format(input, "wavedrom-format").as_deref() { + let format = match diagram_attribute(input, "wavedrom", "format").as_deref() { Some("png") => Format::Png, None | Some("svg") => Format::Svg, Some(other) => { @@ -229,6 +230,32 @@ fn render( ) } +fn svg_option( + renderer: &str, + input: &RawBlockInput<'_>, + 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 image( name: &str, roots: OutputDirectories<'_>, @@ -264,12 +291,9 @@ fn image( .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() - || (format == Format::Svg - && (&input.metadata.options) - .into_iter() - .any(|opt| *opt == "inline"))); + && (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()) @@ -305,7 +329,14 @@ fn image( }; let size = asset::publish(&dir, filename, format, generate).map_err(|e| format!("{name}: {e}"))?; - let image = BlockBuilder::image(physical_target.unwrap_or(image_target)); + 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 target.is_empty() { defaults.push("alt=Diagram".to_owned()); diff --git a/extensions/diagram/src/tikz.rs b/extensions/diagram/src/tikz.rs index d1977352b..6d6fb40b0 100644 --- a/extensions/diagram/src/tikz.rs +++ b/extensions/diagram/src/tikz.rs @@ -7,7 +7,7 @@ use acdc_parser::{DocumentAttributeValue, extensions::BlockStyle}; use super::{ OutputDirectories, asset::{self, Format}, - diagram_source, executable, image, requested_format, style, + diagram_attribute, diagram_source, executable, image, style, }; /// Register the `tikz` style for listing and literal blocks in trusted documents. @@ -51,7 +51,7 @@ pub fn tikz<'a>( return Err("TikZ supports only command=lualatex".into()); } } - let format = match requested_format(input, "tikz-format").as_deref() { + let format = match diagram_attribute(input, "tikz", "format").as_deref() { Some("svg") => Format::Svg, Some("pdf") => Format::Pdf, Some(other) => { diff --git a/extensions/diagram/tests/wavedrom.rs b/extensions/diagram/tests/wavedrom.rs index 096863320..c8e75eb36 100644 --- a/extensions/diagram/tests/wavedrom.rs +++ b/extensions/diagram/tests/wavedrom.rs @@ -143,6 +143,11 @@ fn restrictive_modes_and_invalid_targets_fail_before_execution() -> TestResult { ("[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"), @@ -362,6 +367,7 @@ cp "$(dirname "$0")/result.png" "$4" ":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( From 894ddaacc94584f543a6d5ee2c50e731cfafa833 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 20:09:30 +0100 Subject: [PATCH 17/60] fix(diagram): create owner-only renderer scratch directories on Unix --- acdc-cli/tests/convert/diagram.rs | 44 +++++++++++++++++++++++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 2 ++ extensions/diagram/src/asset.rs | 11 +++++--- 4 files changed, 56 insertions(+), 3 deletions(-) diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 415ec8669..7e2a85795 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -87,6 +87,50 @@ mod active { run_acdc_in(root, &command, stdin) } + #[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 _; diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index bead52238..d6c50d450 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 73789ac37..44580667a 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -60,6 +60,8 @@ If WaveDrom or TikZ fails to generate an image, the default `diagram-on-error=lo 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 `wavedrom-on-error` or `tikz-on-error`, which override `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 diff --git a/extensions/diagram/src/asset.rs b/extensions/diagram/src/asset.rs index e8d41f457..2547fe7a4 100644 --- a/extensions/diagram/src/asset.rs +++ b/extensions/diagram/src/asset.rs @@ -130,9 +130,14 @@ pub(super) fn publish( format: Format, generate: impl FnOnce(&Path, &Path) -> io::Result<()>, ) -> io::Result> { - let scratch = tempfile::Builder::new() - .prefix(".acdc-diagram-") - .tempdir_in(dir)?; + 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)); + } + let scratch = scratch.tempdir_in(dir)?; let output = scratch .path() .join(format!("output.{}", format.extension())); From c3c54dde97b63a1cb41a9dc5b573128120a47153 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 20:10:04 +0100 Subject: [PATCH 18/60] docs(diagram): record real-renderer PDF acceptance for the ACE examples --- extensions/diagram/README.adoc | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 44580667a..e6d482451 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -102,3 +102,12 @@ To verify both formats with the real tools: ---- 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). From ef96432174582b3eeaf1691eeafbe6c54491e8bf Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 20:18:40 +0100 Subject: [PATCH 19/60] feat(diagram): render Graphviz blocks with a caller-selected dot --- AGENTS.md | 2 +- acdc-cli/CHANGELOG.md | 2 + acdc-cli/Cargo.toml | 2 +- acdc-cli/README.adoc | 7 +- .../src/subcommands/convert/extensions.rs | 20 ++++- acdc-cli/tests/convert/diagram.rs | 80 +++++++++++++++++++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 32 +++++--- extensions/diagram/src/asset.rs | 53 +++++++++++- extensions/diagram/src/graphviz.rs | 74 +++++++++++++++++ extensions/diagram/src/lib.rs | 15 ++-- extensions/diagram/src/tikz.rs | 3 +- 12 files changed, 265 insertions(+), 27 deletions(-) create mode 100644 extensions/diagram/src/graphviz.rs diff --git a/AGENTS.md b/AGENTS.md index 3fb1a55dd..02cfea7c5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,7 +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 WaveDrom and TikZ available via `--extension diagram` with caller-selected executables in unsafe mode | +| `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/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index e84cde4bc..1a9a1257d 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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 diff --git a/acdc-cli/Cargo.toml b/acdc-cli/Cargo.toml index 0f1a896c1..1a8c61c17 100644 --- a/acdc-cli/Cargo.toml +++ b/acdc-cli/Cargo.toml @@ -55,7 +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"] # WaveDrom and TikZ; activate with --extension diagram +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 709b32697..e1797cb2a 100644 --- a/acdc-cli/README.adoc +++ b/acdc-cli/README.adoc @@ -130,15 +130,16 @@ 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. -WaveDrom accepts SVG (default) or PNG. TikZ uses LuaLaTeX for PDF and can use pdf2svg for SVG. +Graphviz accepts PNG (default), SVG, or PDF. 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 --wavedrom-cli /opt/bin/wavedrom-cli manual.adoc acdc convert --extension diagram --lualatex /opt/tex/bin/lualatex --pdf2svg /opt/bin/pdf2svg manual.adoc .... -Both tool sets can be supplied together. Diagram blocks run only in unsafe mode (the CLI default). +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. @@ -540,7 +541,7 @@ echo '{"contents":"= Hello","path":"test.adoc","type":"block"}' \ | `diagram` | no -| Makes WaveDrom and TikZ available through `--extension diagram` and caller-supplied tool paths. +| Makes native diagram styles available through `--extension diagram` and caller-supplied tool paths. | `terminal-emulator` | no diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index c8e8c5e82..9b2be5fe6 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -31,7 +31,10 @@ impl Selection { #[cfg(feature = "diagram")] if args.extensions.iter().any(|name| name == "diagram") { return args.diagram.select(args, catalog, asset_base); - } else if args.diagram.wavedrom_cli.is_some() || args.diagram.lualatex.is_some() { + } else if args.diagram.wavedrom_cli.is_some() + || args.diagram.lualatex.is_some() + || args.diagram.graphviz_dot.is_some() + { return Err(miette::miette!( "diagram tool paths require --extension diagram" )); @@ -65,6 +68,9 @@ fn parent(file: Option<&Path>) -> &Path { #[cfg(feature = "diagram")] #[derive(clap::Args, Debug)] pub(super) struct DiagramArgs { + /// Path to the trusted Graphviz dot executable + #[arg(long, value_name = "PATH")] + graphviz_dot: Option, /// Path to the trusted wavedrom-cli executable #[arg(long, value_name = "PATH")] wavedrom_cli: Option, @@ -85,9 +91,9 @@ impl DiagramArgs { asset_base: AssetBase, ) -> Result { use std::collections::{HashMap, hash_map::Entry}; - if self.wavedrom_cli.is_none() && self.lualatex.is_none() { + if self.wavedrom_cli.is_none() && self.lualatex.is_none() && self.graphviz_dot.is_none() { return Err(miette::miette!( - "--extension diagram requires --wavedrom-cli PATH or --lualatex PATH" + "--extension diagram requires --wavedrom-cli PATH, --lualatex PATH, or --graphviz-dot PATH" )); } // The terminal backend displays files from the working directory, including in a pager. @@ -142,6 +148,14 @@ impl DiagramArgs { let output = acdc_diagram::OutputDirectories::new(linked, embedded) .with_imagesoutdir_base(Path::new(".")); let mut registry = Registry::builder(); + if let Some(tool) = &self.graphviz_dot { + let style = acdc_diagram::graphviz(tool, output).map_err(|e| { + miette::miette!("cannot configure Graphviz with {}: {e}", tool.display()) + })?; + registry + .register_block_style(style) + .map_err(|e| error::display(&e))?; + } 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()) diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 7e2a85795..7bbdbe1b3 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -38,6 +38,10 @@ fn diagram_configuration_requires_activation_and_tools() -> TestResult { let dir = tempfile::tempdir()?; for (args, expected) in [ (vec!["--extension", "diagram"], "requires --wavedrom-cli"), + ( + vec!["--graphviz-dot", "missing"], + "require --extension diagram", + ), ( vec!["--wavedrom-cli", "missing"], "require --extension diagram", @@ -87,6 +91,82 @@ mod active { run_acdc_in(root, &command, stdin) } + #[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()?; diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index d6c50d450..39df49f2e 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index e6d482451..47d1c94d4 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -27,7 +27,7 @@ let parsed = builder.build().parse(source, &options)?.finish()?; .... ---- -WaveDrom and TikZ receive the preprocessed body verbatim by default. +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. @@ -35,30 +35,30 @@ Only the attribute step of a `subs` setting affects diagram source. Formatting, 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. -WaveDrom and TikZ use the final segment as the default alternative text, with hyphens and underscores displayed as spaces. +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 source sent to the renderer. Named `target=` and `format=` take precedence. +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 ``. -The `wavedrom-svg-type` and `tikz-svg-type` attributes override the shared setting. Each block can override either with `svg-type=static`, `inline`, or `interactive`. +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. -WaveDrom PNG diagrams use the pixel width and height of the generated raster. +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`. SVG is the default. -Set `:diagram-format: svg` to select a common format for WaveDrom and TikZ. -A block's positional or named format overrides `wavedrom-format` or `tikz-format`, which in turn override `diagram-format`. +Use `[wavedrom,clock,png]` to generate `clock.png`. WaveDrom defaults to SVG. +Set `:diagram-format: svg` to select a common format for all three 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 WaveDrom or TikZ fails to generate an image, the default `diagram-on-error=log` reports a warning at the block and continues conversion. +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 `wavedrom-on-error` or `tikz-on-error`, which override `diagram-on-error` in effect at the block. +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. @@ -82,9 +82,19 @@ 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. +Only the caller selects the executable. Rendering requires unsafe mode. + == Verification -The adapter uses the file-to-file protocol from https://github.com/nlopes/acdc/pull/451[acdc-diagram]. +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. + +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: diff --git a/extensions/diagram/src/asset.rs b/extensions/diagram/src/asset.rs index 2547fe7a4..cf1bac6f9 100644 --- a/extensions/diagram/src/asset.rs +++ b/extensions/diagram/src/asset.rs @@ -73,7 +73,14 @@ impl Format { if svg.len() as u64 > MAX_BYTES { return Err(io::Error::other("invalid SVG output")); } - let document = roxmltree::Document::parse(&svg).map_err(io::Error::other)?; + let document = roxmltree::Document::parse_with_options( + &svg, + roxmltree::ParsingOptions { + allow_dtd: declares_svg_11(&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")); @@ -96,6 +103,22 @@ impl Format { } } +// Graphviz emits this external SVG 1.1 declaration. Only enable DTD parsing for +// that exact prolog (without an internal subset), with no external entity resolver. +fn declares_svg_11(svg: &str) -> bool { + let svg = svg.trim_start_matches('\u{feff}').trim_start(); + let prolog = svg + .strip_prefix("")) + .map_or(svg, |(_, rest)| rest.trim_start()); + prolog.strip_prefix("')) + .is_some_and(|(decl, _)| decl.split_ascii_whitespace().eq( + r#"svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd""# + .split_ascii_whitespace() + )) +} + // Check the raster and its end marker before publishing, without storing a full frame. fn validate_png(file: fs::File) -> io::Result { let invalid = |e: png::DecodingError| { @@ -148,9 +171,18 @@ pub(super) fn publish( } pub(super) fn run(command: &mut Command, dir: &Path, tool: &str) -> io::Result<()> { + run_with_input(command, dir, tool, Stdio::null()) +} + +pub(super) fn run_with_input( + command: &mut Command, + dir: &Path, + tool: &str, + stdin: Stdio, +) -> io::Result<()> { let mut child = command .current_dir(dir) - .stdin(Stdio::null()) + .stdin(stdin) .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn()?; @@ -177,3 +209,20 @@ pub(super) fn run(command: &mut Command, dir: &Path, tool: &str) -> io::Result<( 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/graphviz.rs b/extensions/diagram/src/graphviz.rs new file mode 100644 index 000000000..7470f27dd --- /dev/null +++ b/extensions/diagram/src/graphviz.rs @@ -0,0 +1,74 @@ +//! Graphviz's stdin-to-file 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 `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| { + 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()], + |scratch, output| { + let input_path = scratch.join("input.dot"); + fs::write(&input_path, source.as_bytes())?; + 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_input( + &mut cmd, + roots.embedded, + "dot", + fs::File::open(input_path)?.into(), + ) + }, + ) + }) +} diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs index aa9af7c29..bc1c1fcfb 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -14,10 +14,12 @@ use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; use sha2::{Digest, Sha256}; mod asset; +mod graphviz; mod tikz; mod wavedrom_cli; use asset::Format; +pub use graphviz::graphviz; pub use tikz::tikz; /// Directories used by a converter to resolve relative image references. @@ -225,7 +227,7 @@ fn render( root, input, format, - &source, + [source.as_ref()], |scratch, output| wavedrom_cli::render(tool, &source, format, scratch, output), ) } @@ -256,22 +258,25 @@ fn svg_option( } } -fn image( +fn image<'a>( name: &str, roots: OutputDirectories<'_>, input: &RawBlockInput<'_>, format: Format, - source: &str, + identity: impl IntoIterator, generate: impl FnOnce(&Path, &Path) -> io::Result<()>, ) -> Result { let attrs = input.document_attributes; let args = &input.metadata.attributes; let target = args.get_string("target").unwrap_or_default(); let image_target = if target.is_empty() { - let digest = Sha256::digest(source.as_bytes()); + let mut digest = Sha256::new(); + for part in identity { + digest.update(part); + } format!( "{name}-{}.{}", - URL_SAFE_NO_PAD.encode(digest), + URL_SAFE_NO_PAD.encode(digest.finalize()), format.extension() ) } else { diff --git a/extensions/diagram/src/tikz.rs b/extensions/diagram/src/tikz.rs index 6d6fb40b0..a595089b3 100644 --- a/extensions/diagram/src/tikz.rs +++ b/extensions/diagram/src/tikz.rs @@ -84,7 +84,8 @@ pub fn tikz<'a>( .into_iter() .any(|opt| *opt == "preamble"); let document = latex_document(&diagram_source(input), preamble); - image("tikz", root, input, format, &document, |scratch, output| { + let identity = [document.as_str()]; + image("tikz", root, input, format, identity, |scratch, output| { fs::write(scratch.join("input.tex"), &document)?; asset::run( Command::new(&engine).args([ From ca5058c4f7c4e10b4f5d72cbc3be13946ab6a45f Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 20:39:55 +0100 Subject: [PATCH 20/60] feat(diagram): render Graphviz file macros through the extension host --- acdc-cli/CHANGELOG.md | 2 + acdc-cli/README.adoc | 2 +- .../src/subcommands/convert/extensions.rs | 6 + acdc-cli/tests/convert/diagram.rs | 98 +++++++++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 3 + extensions/diagram/src/graphviz.rs | 183 ++++++++++++---- extensions/diagram/src/lib.rs | 207 ++++++++++++------ 8 files changed, 383 insertions(+), 120 deletions(-) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 1a9a1257d..055ea5114 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/README.adoc b/acdc-cli/README.adoc index e1797cb2a..4eb7bd0e7 100644 --- a/acdc-cli/README.adoc +++ b/acdc-cli/README.adoc @@ -130,7 +130,7 @@ 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. -Graphviz accepts PNG (default), SVG, or PDF. WaveDrom accepts SVG (default) or PNG. TikZ uses LuaLaTeX for PDF and can use pdf2svg for SVG. +Use `graphviz::graphs/chart.dot[svg]` to render an external DOT file as `chart.svg`. Graphviz accepts PNG (default), SVG, or PDF. WaveDrom accepts SVG (default) or PNG. TikZ uses LuaLaTeX for PDF and can use pdf2svg for SVG. [source,console] .... diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 9b2be5fe6..b6db70d43 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -155,6 +155,12 @@ impl DiagramArgs { registry .register_block_style(style) .map_err(|e| error::display(&e))?; + let file_macro = acdc_diagram::graphviz_file(tool, output).map_err(|e| { + miette::miette!("cannot configure Graphviz with {}: {e}", tool.display()) + })?; + registry + .register(file_macro) + .map_err(|e| error::display(&e))?; } if let Some(tool) = &self.wavedrom_cli { let style = acdc_diagram::wavedrom(tool, output).map_err(|e| { diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 7bbdbe1b3..4238e92f8 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -91,6 +91,104 @@ mod active { run_acdc_in(root, &command, stdin) } + #[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()?; diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 39df49f2e..08375663b 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 47d1c94d4..97494e0a2 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -88,11 +88,14 @@ Register `acdc_diagram::graphviz(&dot, &output_dir)` or pass `--extension diagra 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. == Verification 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]. diff --git a/extensions/diagram/src/graphviz.rs b/extensions/diagram/src/graphviz.rs index 7470f27dd..656ec4305 100644 --- a/extensions/diagram/src/graphviz.rs +++ b/extensions/diagram/src/graphviz.rs @@ -2,12 +2,17 @@ use std::{fs, io, path::Path, process::Command}; -use acdc_parser::{DocumentAttributeValue, extensions::BlockStyle}; +use acdc_parser::{ + BlockMetadata, DocumentAttributeValue, + extensions::{ + BlockBuilder, BlockMacro, BlockStyle, MacroExecutionContext, MacroInvocation, MacroTarget, + }, +}; use super::{ - OutputDirectories, + DiagramInput, Directories, OutputDirectories, asset::{self, Format}, - diagram_attribute, diagram_source, executable, image, style, + diagram_attribute, diagram_source, executable, image, recover, require_unsafe, style, }; /// Register the `graphviz` style with a trusted Graphviz `dot` executable. @@ -22,53 +27,135 @@ pub fn graphviz<'a>( // 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| { - 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()); + 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)?)?; + let dirs = Directories::resolve(output_dir.into())?; + Ok(BlockMacro::new("graphviz", move || { + let dirs = dirs.clone(); + let dot = dot.clone(); + move |call: &MacroInvocation<'_>, context: &mut MacroExecutionContext| { + let attrs = (&call.document_attributes).into(); + require_unsafe("Graphviz", 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()); } - } - 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)" + if let Some(subs) = call.attributes.get_string("subs") { + metadata.substitutions = Some(acdc_parser::SubstitutionSpec::Source( + subs.split(',').map(|part| part.trim().to_owned()).collect(), )); } - }; - 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()], - |scratch, output| { - let input_path = scratch.join("input.dot"); - fs::write(&input_path, source.as_bytes())?; - 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_input( - &mut cmd, - roots.embedded, - "dot", - fs::File::open(input_path)?.into(), - ) - }, - ) + 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(&dot, path.parent().unwrap_or(path), dirs.roots(), &input) + .map(|image| { + let attributes = call.named_arguments_source(|name| { + !matches!( + name, + "target" + | "format" + | "layout" + | "on-error" + | "scale" + | "subs" + | "svg-type" + | "dot" + | "graphvizdot" + ) + }); + if attributes.is_empty() { + image + } else { + image.with_attributes(attributes) + } + }), + Err(error) => Err(format!("Graphviz source '{}': {error}", call.target)), + }; + recover(result, "Graphviz", &input, |msg| context.warn(msg)).map(Into::into) + } }) + .with_target(MacroTarget::Required) + .with_positional_attributes(["format"])) +} + +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()], + |scratch, output| { + let input_path = scratch.join("input.dot"); + fs::write(&input_path, source.as_bytes())?; + 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_input( + &mut cmd, + working_dir, + "dot", + fs::File::open(input_path)?.into(), + ) + }, + ) } diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs index bc1c1fcfb..9bd7045d0 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -7,7 +7,8 @@ use std::{ }; use acdc_parser::{ - DocumentAttributeValue, SafeMode, Substitution, VERBATIM, + BlockMetadata, DocumentAttributeValue, SafeMode, Substitution, VERBATIM, + ast::DocumentAttributesRef, extensions::{BlockBuilder, BlockStyle, RawBlockContext, RawBlockInput}, }; use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; @@ -19,7 +20,7 @@ mod tikz; mod wavedrom_cli; use asset::Format; -pub use graphviz::graphviz; +pub use graphviz::{graphviz, graphviz_file}; pub use tikz::tikz; /// Directories used by a converter to resolve relative image references. @@ -84,79 +85,124 @@ fn executable(tool: PathBuf) -> io::Result { 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<'_>, &RawBlockInput<'_>) -> Result + F: Fn(OutputDirectories<'_>, &DiagramInput<'_>) -> Result + Clone + Send + Sync + 'static, { - 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)?; + let dirs = Directories::resolve(output_dir)?; Ok(BlockStyle::raw( label.to_ascii_lowercase(), [RawBlockContext::Listing, RawBlockContext::Literal], move || { - let linked = linked.clone(); - let embedded = embedded.clone(); - let staging = staging.clone(); + let dirs = dirs.clone(); let render = render.clone(); - move |mut input: RawBlockInput<'_>| { - if input - .document_attributes - .get("safe-mode-name") - .and_then(DocumentAttributeValue::text) - != Some(SafeMode::Unsafe.name()) - { - return Err(format!( - "{label} requires unsafe mode to run the configured executable" - )); - } - let roots = OutputDirectories::new(&linked, embedded.as_deref().unwrap_or(&linked)) - .with_imagesoutdir_base(staging.as_deref().unwrap_or(&linked)); - match render(roots, &input) { - Ok(image) => Ok(Some(image)), - Err(error) if abort_on_error(&input, label) => Err(error), - Err(error) => { - let message = format!("Failed to generate image: {error}"); - // The renderer already received its requested substitutions. - // Display that source with ordinary listing escaping. - let listing = - BlockBuilder::listing(format!("{message}\n{}", diagram_source(&input))) - .without_attribute("subs"); - input.warn(message); - Ok(Some(listing)) - } - } + 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 abort_on_error(input: &RawBlockInput<'_>, label: &str) -> bool { +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 @@ -176,7 +222,7 @@ fn abort_on_error(input: &RawBlockInput<'_>, label: &str) -> bool { == Some("abort") } -fn diagram_source<'a>(input: &RawBlockInput<'a>) -> Cow<'a, str> { +fn diagram_source<'a>(input: &DiagramInput<'a>) -> Cow<'a, str> { if input .metadata .uses_substitution(&Substitution::Attributes, VERBATIM) @@ -189,7 +235,7 @@ fn diagram_source<'a>(input: &RawBlockInput<'a>) -> Cow<'a, str> { } fn diagram_attribute<'a>( - input: &RawBlockInput<'a>, + input: &DiagramInput<'a>, renderer: &str, key: &str, ) -> Option> { @@ -205,7 +251,7 @@ fn diagram_attribute<'a>( fn render( tool: &Path, root: OutputDirectories<'_>, - input: &RawBlockInput<'_>, + input: &DiagramInput<'_>, ) -> Result { let attrs = input.document_attributes; let args = &input.metadata.attributes; @@ -234,7 +280,7 @@ fn render( fn svg_option( renderer: &str, - input: &RawBlockInput<'_>, + input: &DiagramInput<'_>, format: Format, ) -> Result, String> { if format != Format::Svg { @@ -258,27 +304,22 @@ fn svg_option( } } -fn image<'a>( +fn image_filename<'a>( name: &str, - roots: OutputDirectories<'_>, - input: &RawBlockInput<'_>, + target: &str, format: Format, identity: impl IntoIterator, - generate: impl FnOnce(&Path, &Path) -> io::Result<()>, -) -> Result { - let attrs = input.document_attributes; - let args = &input.metadata.attributes; - let target = args.get_string("target").unwrap_or_default(); - let image_target = if target.is_empty() { +) -> Result { + if target.is_empty() { let mut digest = Sha256::new(); for part in identity { digest.update(part); } - format!( + Ok(format!( "{name}-{}.{}", URL_SAFE_NO_PAD.encode(digest.finalize()), format.extension() - ) + )) } else { if !target.split('/').all(|part| { !part.is_empty() @@ -290,8 +331,26 @@ fn image<'a>( "{name} target must be a relative path with nonempty segments containing only ASCII letters, digits, hyphens, or underscores" )); } - format!("{target}.{}", format.extension()) - }; + Ok(format!("{target}.{}", format.extension())) + } +} + +fn image<'a>( + name: &str, + roots: OutputDirectories<'_>, + input: &DiagramInput<'_>, + format: Format, + identity: impl IntoIterator, + 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) @@ -320,6 +379,12 @@ fn image<'a>( .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" { @@ -343,7 +408,7 @@ fn image<'a>( image = image.with_attributes(format!("opts={option}")); } let mut defaults = Vec::new(); - if target.is_empty() { + if authored_target.as_deref().unwrap_or_default().is_empty() { defaults.push("alt=Diagram".to_owned()); } if backend.starts_with("html") From f5226299b40504f9c1cf44646c4603e1672daa06 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 20:51:57 +0100 Subject: [PATCH 21/60] feat(diagram): render msc blocks and file macros with mscgen --- acdc-cli/CHANGELOG.md | 2 + acdc-cli/README.adoc | 3 +- .../src/subcommands/convert/extensions.rs | 33 +++++-- acdc-cli/tests/convert/diagram.rs | 64 +++++++++++++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 12 ++- extensions/diagram/src/asset.rs | 11 ++- extensions/diagram/src/file_macro.rs | 75 ++++++++++++++++ extensions/diagram/src/graphviz.rs | 87 +++--------------- extensions/diagram/src/lib.rs | 4 + extensions/diagram/src/msc.rs | 90 +++++++++++++++++++ 11 files changed, 298 insertions(+), 85 deletions(-) create mode 100644 extensions/diagram/src/file_macro.rs create mode 100644 extensions/diagram/src/msc.rs diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 055ea5114..d53c8e691 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/README.adoc b/acdc-cli/README.adoc index 4eb7bd0e7..165ff0310 100644 --- a/acdc-cli/README.adoc +++ b/acdc-cli/README.adoc @@ -130,11 +130,12 @@ 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. WaveDrom accepts SVG (default) or PNG. TikZ uses LuaLaTeX for PDF and can use pdf2svg for SVG. +Use `graphviz::graphs/chart.dot[svg]` to render an external DOT file as `chart.svg`. Graphviz accepts PNG (default), SVG, or PDF. 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 --wavedrom-cli /opt/bin/wavedrom-cli manual.adoc acdc convert --extension diagram --lualatex /opt/tex/bin/lualatex --pdf2svg /opt/bin/pdf2svg manual.adoc .... diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index b6db70d43..6286d912c 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -31,10 +31,7 @@ impl Selection { #[cfg(feature = "diagram")] if args.extensions.iter().any(|name| name == "diagram") { return args.diagram.select(args, catalog, asset_base); - } else if args.diagram.wavedrom_cli.is_some() - || args.diagram.lualatex.is_some() - || args.diagram.graphviz_dot.is_some() - { + } else if args.diagram.has_renderer() { return Err(miette::miette!( "diagram tool paths require --extension diagram" )); @@ -71,6 +68,9 @@ pub(super) struct DiagramArgs { /// 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, @@ -84,6 +84,13 @@ pub(super) struct DiagramArgs { #[cfg(feature = "diagram")] impl DiagramArgs { + fn has_renderer(&self) -> bool { + self.wavedrom_cli.is_some() + || self.lualatex.is_some() + || self.graphviz_dot.is_some() + || self.mscgen.is_some() + } + fn select( &self, args: &Args, @@ -91,9 +98,9 @@ impl DiagramArgs { asset_base: AssetBase, ) -> Result { use std::collections::{HashMap, hash_map::Entry}; - if self.wavedrom_cli.is_none() && self.lualatex.is_none() && self.graphviz_dot.is_none() { + if !self.has_renderer() { return Err(miette::miette!( - "--extension diagram requires --wavedrom-cli PATH, --lualatex PATH, or --graphviz-dot PATH" + "--extension diagram requires --wavedrom-cli PATH, --lualatex PATH, --graphviz-dot PATH, or --mscgen PATH" )); } // The terminal backend displays files from the working directory, including in a pager. @@ -162,6 +169,20 @@ impl DiagramArgs { .register(file_macro) .map_err(|e| error::display(&e))?; } + if let Some(tool) = &self.mscgen { + let style = acdc_diagram::msc(tool, output).map_err(|e| { + miette::miette!("cannot configure mscgen with {}: {e}", tool.display()) + })?; + registry + .register_block_style(style) + .map_err(|e| error::display(&e))?; + let file_macro = acdc_diagram::msc_file(tool, output).map_err(|e| { + miette::miette!("cannot configure mscgen with {}: {e}", tool.display()) + })?; + registry + .register(file_macro) + .map_err(|e| error::display(&e))?; + } 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()) diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 4238e92f8..ebc57dd4d 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -38,6 +38,7 @@ fn diagram_configuration_requires_activation_and_tools() -> TestResult { let dir = tempfile::tempdir()?; for (args, expected) in [ (vec!["--extension", "diagram"], "requires --wavedrom-cli"), + (vec!["--mscgen", "missing"], "require --extension diagram"), ( vec!["--graphviz-dot", "missing"], "require --extension diagram", @@ -91,6 +92,69 @@ mod active { run_acdc_in(root, &command, stdin) } + #[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 { diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 08375663b..7feb97719 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 97494e0a2..8bb945771 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -52,7 +52,7 @@ Use `scale=0.5` to halve those defaults. Explicit `width` and `height` each over 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 all three renderers. +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. @@ -92,8 +92,18 @@ The CLI also registers `graphviz::graphs/chart.dot[svg,alt="*Graph*"]`. In a lib 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. + == Verification +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. diff --git a/extensions/diagram/src/asset.rs b/extensions/diagram/src/asset.rs index cf1bac6f9..18e051bf4 100644 --- a/extensions/diagram/src/asset.rs +++ b/extensions/diagram/src/asset.rs @@ -174,12 +174,19 @@ pub(super) fn run(command: &mut Command, dir: &Path, tool: &str) -> io::Result<( run_with_input(command, dir, tool, Stdio::null()) } -pub(super) fn run_with_input( +pub(super) fn run_with_source( command: &mut Command, dir: &Path, tool: &str, - stdin: Stdio, + scratch: &Path, + source: &str, ) -> io::Result<()> { + let path = scratch.join("stdin"); + fs::write(&path, source.as_bytes())?; + run_with_input(command, dir, tool, fs::File::open(path)?.into()) +} + +fn run_with_input(command: &mut Command, dir: &Path, tool: &str, stdin: Stdio) -> io::Result<()> { let mut child = command .current_dir(dir) .stdin(stdin) diff --git a/extensions/diagram/src/file_macro.rs b/extensions/diagram/src/file_macro.rs new file mode 100644 index 000000000..5b9148b96 --- /dev/null +++ b/extensions/diagram/src/file_macro.rs @@ -0,0 +1,75 @@ +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" + ) && !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/graphviz.rs b/extensions/diagram/src/graphviz.rs index 656ec4305..15feb0991 100644 --- a/extensions/diagram/src/graphviz.rs +++ b/extensions/diagram/src/graphviz.rs @@ -1,18 +1,16 @@ //! Graphviz's stdin-to-file adapter, ported from acdc-diagram (PR #451). -use std::{fs, io, path::Path, process::Command}; +use std::{io, path::Path, process::Command}; use acdc_parser::{ - BlockMetadata, DocumentAttributeValue, - extensions::{ - BlockBuilder, BlockMacro, BlockStyle, MacroExecutionContext, MacroInvocation, MacroTarget, - }, + DocumentAttributeValue, + extensions::{BlockBuilder, BlockMacro, BlockStyle}, }; use super::{ - DiagramInput, Directories, OutputDirectories, + DiagramInput, OutputDirectories, asset::{self, Format}, - diagram_attribute, diagram_source, executable, image, recover, require_unsafe, style, + diagram_attribute, diagram_source, executable, file_macro, image, style, }; /// Register the `graphviz` style with a trusted Graphviz `dot` executable. @@ -42,66 +40,12 @@ pub fn graphviz_file<'a>( output_dir: impl Into>, ) -> io::Result { let dot = executable(std::path::absolute(dot)?)?; - let dirs = Directories::resolve(output_dir.into())?; - Ok(BlockMacro::new("graphviz", move || { - let dirs = dirs.clone(); - let dot = dot.clone(); - move |call: &MacroInvocation<'_>, context: &mut MacroExecutionContext| { - let attrs = (&call.document_attributes).into(); - require_unsafe("Graphviz", 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(acdc_parser::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(&dot, path.parent().unwrap_or(path), dirs.roots(), &input) - .map(|image| { - let attributes = call.named_arguments_source(|name| { - !matches!( - name, - "target" - | "format" - | "layout" - | "on-error" - | "scale" - | "subs" - | "svg-type" - | "dot" - | "graphvizdot" - ) - }); - if attributes.is_empty() { - image - } else { - image.with_attributes(attributes) - } - }), - Err(error) => Err(format!("Graphviz source '{}': {error}", call.target)), - }; - recover(result, "Graphviz", &input, |msg| context.warn(msg)).map(Into::into) - } - }) - .with_target(MacroTarget::Required) - .with_positional_attributes(["format"])) + file_macro( + "Graphviz", + output_dir.into(), + &["layout", "dot", "graphvizdot"], + move |dir, roots, input| render(&dot, dir, roots, input), + ) } fn render( @@ -141,8 +85,6 @@ fn render( format, [layout.unwrap_or_default(), "\0", source.as_ref()], |scratch, output| { - let input_path = scratch.join("input.dot"); - fs::write(&input_path, source.as_bytes())?; let mut cmd = Command::new(dot); cmd.arg("-o") .arg(output) @@ -150,12 +92,7 @@ fn render( if let Some(layout) = layout { cmd.arg(format!("-K{layout}")); } - asset::run_with_input( - &mut cmd, - working_dir, - "dot", - fs::File::open(input_path)?.into(), - ) + asset::run_with_source(&mut cmd, working_dir, "dot", scratch, &source) }, ) } diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs index 9bd7045d0..f3c95f234 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -15,12 +15,16 @@ use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; use sha2::{Digest, Sha256}; mod asset; +mod file_macro; mod graphviz; +mod msc; mod tikz; mod wavedrom_cli; use asset::Format; +use file_macro::file_macro; pub use graphviz::{graphviz, graphviz_file}; +pub use msc::{msc, msc_file}; pub use tikz::tikz; /// Directories used by a converter to resolve relative image references. diff --git a/extensions/diagram/src/msc.rs b/extensions/diagram/src/msc.rs new file mode 100644 index 000000000..28b7cb9d3 --- /dev/null +++ b/extensions/diagram/src/msc.rs @@ -0,0 +1,90 @@ +//! 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()], + |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) + }, + ) +} From 27c620a7c5b0314ec9826549b7500c9e96afe673 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:09:21 +0100 Subject: [PATCH 22/60] feat(diagram): render dpic blocks and file macros as SVG --- acdc-cli/CHANGELOG.md | 2 + acdc-cli/README.adoc | 3 +- .../src/subcommands/convert/extensions.rs | 87 +++++++++----- acdc-cli/tests/convert/diagram.rs | 108 ++++++++++++++++++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 9 ++ extensions/diagram/src/asset.rs | 41 ++++++- extensions/diagram/src/dpic.rs | 104 +++++++++++++++++ extensions/diagram/src/lib.rs | 2 + 9 files changed, 324 insertions(+), 34 deletions(-) create mode 100644 extensions/diagram/src/dpic.rs diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index d53c8e691..d5028f610 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/README.adoc b/acdc-cli/README.adoc index 165ff0310..d1dfc8c7d 100644 --- a/acdc-cli/README.adoc +++ b/acdc-cli/README.adoc @@ -130,12 +130,13 @@ 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. 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. +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. 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 --wavedrom-cli /opt/bin/wavedrom-cli manual.adoc acdc convert --extension diagram --lualatex /opt/tex/bin/lualatex --pdf2svg /opt/bin/pdf2svg manual.adoc .... diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 6286d912c..edb9f309c 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -1,4 +1,8 @@ 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; @@ -65,6 +69,9 @@ fn parent(file: Option<&Path>) -> &Path { #[cfg(feature = "diagram")] #[derive(clap::Args, Debug)] pub(super) struct DiagramArgs { + /// 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, @@ -89,6 +96,7 @@ impl DiagramArgs { || self.lualatex.is_some() || self.graphviz_dot.is_some() || self.mscgen.is_some() + || self.dpic.is_some() } fn select( @@ -100,7 +108,7 @@ impl DiagramArgs { use std::collections::{HashMap, hash_map::Entry}; if !self.has_renderer() { return Err(miette::miette!( - "--extension diagram requires --wavedrom-cli PATH, --lualatex PATH, --graphviz-dot PATH, or --mscgen PATH" + "--extension diagram requires --wavedrom-cli PATH, --lualatex PATH, --graphviz-dot PATH, --mscgen PATH, or --dpic PATH" )); } // The terminal backend displays files from the working directory, including in a pager. @@ -151,37 +159,38 @@ impl DiagramArgs { linked: &Path, embedded: &Path, ) -> Result> { - use acdc_parser::extensions::Registry; - let output = acdc_diagram::OutputDirectories::new(linked, embedded) - .with_imagesoutdir_base(Path::new(".")); + let output = + OutputDirectories::new(linked, embedded).with_imagesoutdir_base(Path::new(".")); let mut registry = Registry::builder(); if let Some(tool) = &self.graphviz_dot { - let style = acdc_diagram::graphviz(tool, output).map_err(|e| { - miette::miette!("cannot configure Graphviz with {}: {e}", tool.display()) - })?; - registry - .register_block_style(style) - .map_err(|e| error::display(&e))?; - let file_macro = acdc_diagram::graphviz_file(tool, output).map_err(|e| { - miette::miette!("cannot configure Graphviz with {}: {e}", tool.display()) - })?; - registry - .register(file_macro) - .map_err(|e| error::display(&e))?; + register_file_renderer( + &mut registry, + "Graphviz", + tool, + output, + acdc_diagram::graphviz, + acdc_diagram::graphviz_file, + )?; } if let Some(tool) = &self.mscgen { - let style = acdc_diagram::msc(tool, output).map_err(|e| { - miette::miette!("cannot configure mscgen with {}: {e}", tool.display()) - })?; - registry - .register_block_style(style) - .map_err(|e| error::display(&e))?; - let file_macro = acdc_diagram::msc_file(tool, output).map_err(|e| { - miette::miette!("cannot configure mscgen with {}: {e}", tool.display()) - })?; - registry - .register(file_macro) - .map_err(|e| error::display(&e))?; + 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.wavedrom_cli { let style = acdc_diagram::wavedrom(tool, output).map_err(|e| { @@ -208,3 +217,25 @@ impl DiagramArgs { .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/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index ebc57dd4d..38af481c3 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -38,6 +38,7 @@ fn diagram_configuration_requires_activation_and_tools() -> TestResult { let dir = tempfile::tempdir()?; for (args, expected) in [ (vec!["--extension", "diagram"], "requires --wavedrom-cli"), + (vec!["--dpic", "missing"], "require --extension diagram"), (vec!["--mscgen", "missing"], "require --extension diagram"), ( vec!["--graphviz-dot", "missing"], @@ -92,6 +93,113 @@ mod active { run_acdc_in(root, &command, stdin) } + #[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()?; diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 7feb97719..80820e799 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 8bb945771..20506beeb 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -100,8 +100,17 @@ Both forms default to PNG. Select SVG with the positional format, `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. + == Verification +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. diff --git a/extensions/diagram/src/asset.rs b/extensions/diagram/src/asset.rs index 18e051bf4..c0000383f 100644 --- a/extensions/diagram/src/asset.rs +++ b/extensions/diagram/src/asset.rs @@ -8,6 +8,8 @@ use std::{ use svgtypes::{Length, LengthUnit, ViewBox}; +const MAX_BYTES: u64 = 16 * 1024 * 1024; + pub(super) struct ImageSize { pub(super) width: f64, pub(super) height: f64, @@ -58,7 +60,6 @@ impl Format { } pub(super) fn validate(self, path: &Path) -> io::Result> { - const MAX_BYTES: u64 = 16 * 1024 * 1024; let meta = fs::symlink_metadata(path)?; if !meta.is_file() || meta.len() > MAX_BYTES { return Err(io::Error::other( @@ -171,7 +172,7 @@ pub(super) fn publish( } pub(super) fn run(command: &mut Command, dir: &Path, tool: &str) -> io::Result<()> { - run_with_input(command, dir, tool, Stdio::null()) + run_redirected(command, dir, tool, Stdio::null(), None) } pub(super) fn run_with_source( @@ -183,14 +184,35 @@ pub(super) fn run_with_source( ) -> io::Result<()> { let path = scratch.join("stdin"); fs::write(&path, source.as_bytes())?; - run_with_input(command, dir, tool, fs::File::open(path)?.into()) + run_redirected(command, dir, tool, fs::File::open(path)?.into(), None) +} + +/// 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<()> { + let file = fs::File::create_new(output)?; + run_redirected(command, dir, tool, Stdio::null(), Some(&file)) } -fn run_with_input(command: &mut Command, dir: &Path, tool: &str, stdin: Stdio) -> io::Result<()> { +fn run_redirected( + command: &mut Command, + dir: &Path, + tool: &str, + stdin: Stdio, + output: Option<&fs::File>, +) -> io::Result<()> { + let stdout = match output { + Some(file) => Stdio::from(file.try_clone()?), + None => Stdio::null(), + }; let mut child = command .current_dir(dir) .stdin(stdin) - .stdout(Stdio::null()) + .stdout(stdout) .stderr(Stdio::null()) .spawn()?; let deadline = Instant::now() + Duration::from_secs(30); @@ -203,6 +225,15 @@ fn run_with_input(command: &mut Command, dir: &Path, tool: &str, stdin: Stdio) - 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( diff --git a/extensions/diagram/src/dpic.rs b/extensions/diagram/src/dpic.rs new file mode 100644 index 000000000..385754656 --- /dev/null +++ b/extensions/diagram/src/dpic.rs @@ -0,0 +1,104 @@ +//! 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::{self, Format}, + diagram_attribute, diagram_source, executable, file_macro, image, 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 { + if input.metadata.attributes.get("dpic").is_some() + || input.document_attributes.get("dpic").is_some() + { + return Err("set the dpic executable when registering the diagram".into()); + } + if let Some(format) = diagram_attribute(input, "dpic", "format").as_deref() + && format != "svg" + { + return Err(format!("unsupported dpic format '{format}' (expected svg)")); + } + let source = diagram_source(input); + image( + "dpic", + roots, + input, + Format::Svg, + [source.as_ref()], + |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/lib.rs b/extensions/diagram/src/lib.rs index f3c95f234..dd86a66de 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -15,6 +15,7 @@ use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; use sha2::{Digest, Sha256}; mod asset; +mod dpic; mod file_macro; mod graphviz; mod msc; @@ -22,6 +23,7 @@ mod tikz; mod wavedrom_cli; use asset::Format; +pub use dpic::{dpic, dpic_file}; use file_macro::file_macro; pub use graphviz::{graphviz, graphviz_file}; pub use msc::{msc, msc_file}; From 3ed7f879999fb8d0f25b8dcfb4036501bc95c78e Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:16:13 +0100 Subject: [PATCH 23/60] feat(diagram): render Pikchr blocks and file macros as SVG --- acdc-cli/CHANGELOG.md | 2 + acdc-cli/README.adoc | 3 +- .../src/subcommands/convert/extensions.rs | 16 ++- acdc-cli/tests/convert/diagram.rs | 121 ++++++++++++++++++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 8 ++ extensions/diagram/src/dpic.rs | 44 ++----- extensions/diagram/src/lib.rs | 34 +++++ extensions/diagram/src/pikchr.rs | 102 +++++++++++++++ 9 files changed, 297 insertions(+), 35 deletions(-) create mode 100644 extensions/diagram/src/pikchr.rs diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index d5028f610..0fcb422ae 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/README.adoc b/acdc-cli/README.adoc index d1dfc8c7d..01f147091 100644 --- a/acdc-cli/README.adoc +++ b/acdc-cli/README.adoc @@ -130,13 +130,14 @@ 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. 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. +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 --wavedrom-cli /opt/bin/wavedrom-cli manual.adoc acdc convert --extension diagram --lualatex /opt/tex/bin/lualatex --pdf2svg /opt/bin/pdf2svg manual.adoc .... diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index edb9f309c..2c32b7d1d 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -69,6 +69,9 @@ fn parent(file: Option<&Path>) -> &Path { #[cfg(feature = "diagram")] #[derive(clap::Args, Debug)] pub(super) struct DiagramArgs { + /// 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, @@ -97,6 +100,7 @@ impl DiagramArgs { || self.graphviz_dot.is_some() || self.mscgen.is_some() || self.dpic.is_some() + || self.pikchr.is_some() } fn select( @@ -108,7 +112,7 @@ impl DiagramArgs { use std::collections::{HashMap, hash_map::Entry}; if !self.has_renderer() { return Err(miette::miette!( - "--extension diagram requires --wavedrom-cli PATH, --lualatex PATH, --graphviz-dot PATH, --mscgen PATH, or --dpic PATH" + "--extension diagram requires --wavedrom-cli PATH, --lualatex PATH, --graphviz-dot PATH, --mscgen PATH, --dpic PATH, or --pikchr PATH" )); } // The terminal backend displays files from the working directory, including in a pager. @@ -192,6 +196,16 @@ impl DiagramArgs { 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.wavedrom_cli { let style = acdc_diagram::wavedrom(tool, output).map_err(|e| { miette::miette!("cannot configure WaveDrom with {}: {e}", tool.display()) diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 38af481c3..cf328e350 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -38,6 +38,7 @@ fn diagram_configuration_requires_activation_and_tools() -> TestResult { let dir = tempfile::tempdir()?; for (args, expected) in [ (vec!["--extension", "diagram"], "requires --wavedrom-cli"), + (vec!["--pikchr", "missing"], "require --extension diagram"), (vec!["--dpic", "missing"], "require --extension diagram"), (vec!["--mscgen", "missing"], "require --extension diagram"), ( @@ -93,6 +94,126 @@ mod active { run_acdc_in(root, &command, stdin) } + #[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()?; diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 80820e799..ef2833271 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 20506beeb..425323264 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -107,8 +107,16 @@ In a library, register the block style returned by `acdc_diagram::dpic` and the 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. + == Verification +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. diff --git a/extensions/diagram/src/dpic.rs b/extensions/diagram/src/dpic.rs index 385754656..7bcb9282d 100644 --- a/extensions/diagram/src/dpic.rs +++ b/extensions/diagram/src/dpic.rs @@ -9,11 +9,7 @@ use std::{ use acdc_parser::extensions::{BlockBuilder, BlockMacro, BlockStyle}; -use super::{ - DiagramInput, OutputDirectories, - asset::{self, Format}, - diagram_attribute, diagram_source, executable, file_macro, image, style, -}; +use super::{DiagramInput, OutputDirectories, asset, executable, file_macro, render_svg, style}; /// Register the `dpic` listing and literal block style with a caller-selected executable. /// @@ -52,34 +48,16 @@ fn render( roots: OutputDirectories<'_>, input: &DiagramInput<'_>, ) -> Result { - if input.metadata.attributes.get("dpic").is_some() - || input.document_attributes.get("dpic").is_some() - { - return Err("set the dpic executable when registering the diagram".into()); - } - if let Some(format) = diagram_attribute(input, "dpic", "format").as_deref() - && format != "svg" - { - return Err(format!("unsupported dpic format '{format}' (expected svg)")); - } - let source = diagram_source(input); - image( - "dpic", - roots, - input, - Format::Svg, - [source.as_ref()], - |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, - ) - }, - ) + render_svg("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<()> { diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs index dd86a66de..cf1862ce3 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -19,6 +19,7 @@ mod dpic; mod file_macro; mod graphviz; mod msc; +mod pikchr; mod tikz; mod wavedrom_cli; @@ -27,6 +28,7 @@ pub use dpic::{dpic, dpic_file}; use file_macro::file_macro; pub use graphviz::{graphviz, graphviz_file}; 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. @@ -310,6 +312,38 @@ fn svg_option( } } +/// SVG-only tools whose executable attribute has the same name as the style. +fn render_svg( + name: &str, + roots: OutputDirectories<'_>, + input: &DiagramInput<'_>, + generate: impl FnOnce(&str, &Path, &Path) -> io::Result<()>, +) -> Result { + if input.metadata.attributes.get(name).is_some() + || input.document_attributes.get(name).is_some() + { + return Err(format!( + "set the {name} 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, + [source.as_ref()], + |scratch, output| generate(&source, scratch, output), + ) +} + fn image_filename<'a>( name: &str, target: &str, diff --git a/extensions/diagram/src/pikchr.rs b/extensions/diagram/src/pikchr.rs new file mode 100644 index 000000000..b599bf052 --- /dev/null +++ b/extensions/diagram/src/pikchr.rs @@ -0,0 +1,102 @@ +//! 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", 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) +} From 83753809d8ceef4fff6973e63e281352eff960c7 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:21:47 +0100 Subject: [PATCH 24/60] feat(diagram): render GoAT ASCII diagrams as SVG --- acdc-cli/CHANGELOG.md | 2 + acdc-cli/README.adoc | 1 + .../src/subcommands/convert/extensions.rs | 16 +++- acdc-cli/tests/convert/diagram.rs | 90 +++++++++++++++++++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 8 ++ extensions/diagram/src/asset.rs | 13 +-- extensions/diagram/src/dpic.rs | 2 +- extensions/diagram/src/goat.rs | 68 ++++++++++++++ extensions/diagram/src/graphviz.rs | 2 +- extensions/diagram/src/lib.rs | 8 +- extensions/diagram/src/msc.rs | 2 +- extensions/diagram/src/pikchr.rs | 2 +- 13 files changed, 204 insertions(+), 12 deletions(-) create mode 100644 extensions/diagram/src/goat.rs diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 0fcb422ae..f6313714a 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/README.adoc b/acdc-cli/README.adoc index 01f147091..ddfdbf436 100644 --- a/acdc-cli/README.adoc +++ b/acdc-cli/README.adoc @@ -138,6 +138,7 @@ 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 --wavedrom-cli /opt/bin/wavedrom-cli manual.adoc acdc convert --extension diagram --lualatex /opt/tex/bin/lualatex --pdf2svg /opt/bin/pdf2svg manual.adoc .... diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 2c32b7d1d..664b0296c 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -69,6 +69,9 @@ fn parent(file: Option<&Path>) -> &Path { #[cfg(feature = "diagram")] #[derive(clap::Args, Debug)] pub(super) struct DiagramArgs { + /// 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, @@ -101,6 +104,7 @@ impl DiagramArgs { || self.mscgen.is_some() || self.dpic.is_some() || self.pikchr.is_some() + || self.goat.is_some() } fn select( @@ -112,7 +116,7 @@ impl DiagramArgs { use std::collections::{HashMap, hash_map::Entry}; if !self.has_renderer() { return Err(miette::miette!( - "--extension diagram requires --wavedrom-cli PATH, --lualatex PATH, --graphviz-dot PATH, --mscgen PATH, --dpic PATH, or --pikchr PATH" + "--extension diagram requires --wavedrom-cli PATH, --lualatex PATH, --graphviz-dot PATH, --mscgen PATH, --dpic PATH, --pikchr PATH, or --goat PATH" )); } // The terminal backend displays files from the working directory, including in a pager. @@ -206,6 +210,16 @@ impl DiagramArgs { 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.wavedrom_cli { let style = acdc_diagram::wavedrom(tool, output).map_err(|e| { miette::miette!("cannot configure WaveDrom with {}: {e}", tool.display()) diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index cf328e350..3d86f6a40 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -38,6 +38,7 @@ fn diagram_configuration_requires_activation_and_tools() -> TestResult { let dir = tempfile::tempdir()?; for (args, expected) in [ (vec!["--extension", "diagram"], "requires --wavedrom-cli"), + (vec!["--goat", "missing"], "require --extension diagram"), (vec!["--pikchr", "missing"], "require --extension diagram"), (vec!["--dpic", "missing"], "require --extension diagram"), (vec!["--mscgen", "missing"], "require --extension diagram"), @@ -94,6 +95,95 @@ mod active { run_acdc_in(root, &command, stdin) } + #[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()?; diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index ef2833271..9f8c49a0e 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 425323264..5d8bdfa34 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -113,8 +113,16 @@ Use `--extension diagram --pikchr /usr/bin/pikchr` to render a listing or litera 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. + == Verification +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. diff --git a/extensions/diagram/src/asset.rs b/extensions/diagram/src/asset.rs index c0000383f..284d6d494 100644 --- a/extensions/diagram/src/asset.rs +++ b/extensions/diagram/src/asset.rs @@ -181,10 +181,11 @@ pub(super) fn run_with_source( 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(), None) + run_redirected(command, dir, tool, fs::File::open(path)?.into(), stdout) } /// Stream renderer stdout directly to the unpublished asset. @@ -194,8 +195,7 @@ pub(super) fn run_to_file( tool: &str, output: &Path, ) -> io::Result<()> { - let file = fs::File::create_new(output)?; - run_redirected(command, dir, tool, Stdio::null(), Some(&file)) + run_redirected(command, dir, tool, Stdio::null(), Some(output)) } fn run_redirected( @@ -203,9 +203,10 @@ fn run_redirected( dir: &Path, tool: &str, stdin: Stdio, - output: Option<&fs::File>, + output: Option<&Path>, ) -> io::Result<()> { - let stdout = match output { + let output = output.map(fs::File::create_new).transpose()?; + let stdout = match &output { Some(file) => Stdio::from(file.try_clone()?), None => Stdio::null(), }; @@ -225,7 +226,7 @@ fn run_redirected( Err(error) => break error, Ok(None) => {} } - if let Some(file) = output { + 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")); diff --git a/extensions/diagram/src/dpic.rs b/extensions/diagram/src/dpic.rs index 7bcb9282d..36b112c89 100644 --- a/extensions/diagram/src/dpic.rs +++ b/extensions/diagram/src/dpic.rs @@ -48,7 +48,7 @@ fn render( roots: OutputDirectories<'_>, input: &DiagramInput<'_>, ) -> Result { - render_svg("dpic", roots, input, |source, scratch, output| { + render_svg("dpic", roots, input, &[], |source, scratch, output| { let path = scratch.join("input.pic"); write_picture(&path, source)?; asset::run_to_file( diff --git a/extensions/diagram/src/goat.rs b/extensions/diagram/src/goat.rs new file mode 100644 index 000000000..05a6265d5 --- /dev/null +++ b/extensions/diagram/src/goat.rs @@ -0,0 +1,68 @@ +//! 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", 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 index 15feb0991..80e60165e 100644 --- a/extensions/diagram/src/graphviz.rs +++ b/extensions/diagram/src/graphviz.rs @@ -92,7 +92,7 @@ fn render( if let Some(layout) = layout { cmd.arg(format!("-K{layout}")); } - asset::run_with_source(&mut cmd, working_dir, "dot", scratch, &source) + 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 index cf1862ce3..d03a54f2d 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -17,6 +17,7 @@ use sha2::{Digest, Sha256}; mod asset; mod dpic; mod file_macro; +mod goat; mod graphviz; mod msc; mod pikchr; @@ -26,6 +27,7 @@ mod wavedrom_cli; use asset::Format; 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 msc::{msc, msc_file}; pub use pikchr::{pikchr, pikchr_file}; @@ -317,6 +319,7 @@ fn render_svg( name: &str, roots: OutputDirectories<'_>, input: &DiagramInput<'_>, + arguments: &[&str], generate: impl FnOnce(&str, &Path, &Path) -> io::Result<()>, ) -> Result { if input.metadata.attributes.get(name).is_some() @@ -339,7 +342,10 @@ fn render_svg( roots, input, Format::Svg, - [source.as_ref()], + arguments + .iter() + .flat_map(|arg| [*arg, "\0"]) + .chain([source.as_ref()]), |scratch, output| generate(&source, scratch, output), ) } diff --git a/extensions/diagram/src/msc.rs b/extensions/diagram/src/msc.rs index 28b7cb9d3..efec237d3 100644 --- a/extensions/diagram/src/msc.rs +++ b/extensions/diagram/src/msc.rs @@ -84,7 +84,7 @@ fn render( if let Some(font) = font { cmd.arg("-F").arg(font); } - asset::run_with_source(cmd.arg("-"), dir, "mscgen", scratch, &source) + 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 index b599bf052..931cd45f9 100644 --- a/extensions/diagram/src/pikchr.rs +++ b/extensions/diagram/src/pikchr.rs @@ -48,7 +48,7 @@ fn render( roots: OutputDirectories<'_>, input: &DiagramInput<'_>, ) -> Result { - render_svg("pikchr", roots, input, |source, scratch, output| { + render_svg("pikchr", roots, input, &[], |source, scratch, output| { let path = scratch.join("input.pikchr"); fs::write(&path, source)?; let result = asset::run_to_file( From f342d3e4045d5fe0f8772d21f5fd1e9189972beb Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:25:18 +0100 Subject: [PATCH 25/60] feat(diagram): render Bytefield blocks and file macros as SVG --- acdc-cli/CHANGELOG.md | 2 + acdc-cli/README.adoc | 1 + .../src/subcommands/convert/extensions.rs | 16 ++- acdc-cli/tests/convert/diagram.rs | 103 ++++++++++++++++++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 8 ++ extensions/diagram/src/bytefield.rs | 63 +++++++++++ extensions/diagram/src/dpic.rs | 27 +++-- extensions/diagram/src/goat.rs | 27 +++-- extensions/diagram/src/lib.rs | 10 +- extensions/diagram/src/pikchr.rs | 39 ++++--- 11 files changed, 257 insertions(+), 41 deletions(-) create mode 100644 extensions/diagram/src/bytefield.rs diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index f6313714a..0861136ec 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/README.adoc b/acdc-cli/README.adoc index ddfdbf436..91301f4f2 100644 --- a/acdc-cli/README.adoc +++ b/acdc-cli/README.adoc @@ -139,6 +139,7 @@ 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 --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 .... diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 664b0296c..97cf90e42 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -69,6 +69,9 @@ fn parent(file: Option<&Path>) -> &Path { #[cfg(feature = "diagram")] #[derive(clap::Args, Debug)] pub(super) struct DiagramArgs { + /// 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, @@ -105,6 +108,7 @@ impl DiagramArgs { || self.dpic.is_some() || self.pikchr.is_some() || self.goat.is_some() + || self.bytefield_svg.is_some() } fn select( @@ -116,7 +120,7 @@ impl DiagramArgs { use std::collections::{HashMap, hash_map::Entry}; if !self.has_renderer() { return Err(miette::miette!( - "--extension diagram requires --wavedrom-cli PATH, --lualatex PATH, --graphviz-dot PATH, --mscgen PATH, --dpic PATH, --pikchr PATH, or --goat PATH" + "--extension diagram requires --wavedrom-cli PATH, --lualatex PATH, --graphviz-dot PATH, --mscgen PATH, --dpic PATH, --pikchr PATH, --goat PATH, or --bytefield-svg PATH" )); } // The terminal backend displays files from the working directory, including in a pager. @@ -220,6 +224,16 @@ impl DiagramArgs { 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()) diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 3d86f6a40..2ba270cb3 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -38,6 +38,10 @@ fn diagram_configuration_requires_activation_and_tools() -> TestResult { let dir = tempfile::tempdir()?; for (args, expected) in [ (vec!["--extension", "diagram"], "requires --wavedrom-cli"), + ( + 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"), @@ -95,6 +99,105 @@ mod active { run_acdc_in(root, &command, stdin) } + #[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()?; diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 9f8c49a0e..37c95aca5 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 5d8bdfa34..7ddde26f2 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -119,8 +119,16 @@ Use `--extension diagram --goat /usr/bin/goat` to render ASCII art from a `[goat 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. + == 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. 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 index 36b112c89..3e32a260d 100644 --- a/extensions/diagram/src/dpic.rs +++ b/extensions/diagram/src/dpic.rs @@ -48,16 +48,23 @@ fn render( roots: OutputDirectories<'_>, input: &DiagramInput<'_>, ) -> Result { - render_svg("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, - ) - }) + 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<()> { diff --git a/extensions/diagram/src/goat.rs b/extensions/diagram/src/goat.rs index 05a6265d5..31ec63a54 100644 --- a/extensions/diagram/src/goat.rs +++ b/extensions/diagram/src/goat.rs @@ -55,14 +55,21 @@ fn render( if let Some(color) = light.as_deref() { args.extend(["-sls", color]); } - render_svg("goat", roots, input, &args, |source, scratch, output| { - asset::run_with_source( - Command::new(tool).args(&args), - dir, - "goat", - scratch, - source, - Some(output), - ) - }) + 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/lib.rs b/extensions/diagram/src/lib.rs index d03a54f2d..3467b3a52 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -15,6 +15,7 @@ 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; @@ -25,6 +26,7 @@ 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}; @@ -314,19 +316,19 @@ fn svg_option( } } -/// SVG-only tools whose executable attribute has the same name as the style. 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(name).is_some() - || input.document_attributes.get(name).is_some() + if input.metadata.attributes.get(tool_attribute).is_some() + || input.document_attributes.get(tool_attribute).is_some() { return Err(format!( - "set the {name} executable when registering the diagram" + "set the {tool_attribute} executable when registering the diagram" )); } if let Some(format) = diagram_attribute(input, name, "format").as_deref() diff --git a/extensions/diagram/src/pikchr.rs b/extensions/diagram/src/pikchr.rs index 931cd45f9..329016b16 100644 --- a/extensions/diagram/src/pikchr.rs +++ b/extensions/diagram/src/pikchr.rs @@ -48,23 +48,30 @@ fn render( roots: OutputDirectories<'_>, input: &DiagramInput<'_>, ) -> Result { - render_svg("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}"))) + 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, } - (result, _) => result, - } - }) + }, + ) } // Pikchr writes parser diagnostics to stdout. Older CLIs return an HTML fragment From 9a26bab9ac3e6e2fd3f5f8a306a1eb40ac6d4775 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:37:23 +0100 Subject: [PATCH 26/60] feat(diagram): render blockdiag blocks and file macros --- acdc-cli/CHANGELOG.md | 2 + acdc-cli/README.adoc | 1 + .../src/subcommands/convert/extensions.rs | 21 +++ acdc-cli/tests/convert/diagram.rs | 60 +++++++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 4 + extensions/diagram/src/asset.rs | 14 +- extensions/diagram/src/lib.rs | 1 + extensions/diagram/src/renderer.rs | 158 ++++++++++++++++++ 9 files changed, 256 insertions(+), 7 deletions(-) create mode 100644 extensions/diagram/src/renderer.rs diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 0861136ec..0c39b120c 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/README.adoc b/acdc-cli/README.adoc index 91301f4f2..89e399ace 100644 --- a/acdc-cli/README.adoc +++ b/acdc-cli/README.adoc @@ -139,6 +139,7 @@ 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 diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 97cf90e42..8065e3c0e 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -69,6 +69,9 @@ fn parent(file: Option<&Path>) -> &Path { #[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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -100,6 +103,14 @@ pub(super) struct DiagramArgs { #[cfg(feature = "diagram")] impl DiagramArgs { + fn configured_renderers( + &self, + ) -> impl Iterator { + [(acdc_diagram::renderer::BLOCKDIAG, self.blockdiag.as_deref())] + .into_iter() + .filter_map(|(renderer, path): (_, Option<&Path>)| path.map(|p| (renderer, p))) + } + fn has_renderer(&self) -> bool { self.wavedrom_cli.is_some() || self.lualatex.is_some() @@ -109,6 +120,7 @@ impl DiagramArgs { || self.pikchr.is_some() || self.goat.is_some() || self.bytefield_svg.is_some() + || self.configured_renderers().next().is_some() } fn select( @@ -250,6 +262,15 @@ impl DiagramArgs { .register_block_style(style) .map_err(|e| error::display(&e))?; } + for (renderer, tool) in self.configured_renderers() { + let (style, file) = renderer + .processors(tool, output) + .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))?; + } let mut catalog = available.clone(); catalog .register("diagram", registry.build()) diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 2ba270cb3..491967da9 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -99,6 +99,66 @@ mod active { 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""#, + ) + } + + fn tool_sample( + style: &str, + flag: &str, + body: &str, + format: &str, + renderer: &str, + ) -> TestResult { + let temp = tempfile::tempdir()?; + let root = temp.path(); + fs::write(root.join("chart.source"), body)?; + fs::write( + root.join("doc.adoc"), + format!( + "[{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 run = run_acdc_in( + root, + &[ + "convert", + "--extension", + "diagram", + flag, + "./renderer", + "--fail-on-warnings", + "doc.adoc", + ], + 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()?; diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 37c95aca5..d25c3113e 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 7ddde26f2..cad326293 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -125,6 +125,10 @@ Use `--extension diagram --bytefield-svg /usr/bin/bytefield-svg` to render packe 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`. + == 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. diff --git a/extensions/diagram/src/asset.rs b/extensions/diagram/src/asset.rs index 284d6d494..4a96aec9e 100644 --- a/extensions/diagram/src/asset.rs +++ b/extensions/diagram/src/asset.rs @@ -77,7 +77,7 @@ impl Format { let document = roxmltree::Document::parse_with_options( &svg, roxmltree::ParsingOptions { - allow_dtd: declares_svg_11(&svg), + allow_dtd: declares_standard_svg(&svg), ..Default::default() }, ) @@ -104,9 +104,9 @@ impl Format { } } -// Graphviz emits this external SVG 1.1 declaration. Only enable DTD parsing for +// 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_svg_11(svg: &str) -> bool { +fn declares_standard_svg(svg: &str) -> bool { let svg = svg.trim_start_matches('\u{feff}').trim_start(); let prolog = svg .strip_prefix(" bool { .map_or(svg, |(_, rest)| rest.trim_start()); prolog.strip_prefix("')) - .is_some_and(|(decl, _)| decl.split_ascii_whitespace().eq( - r#"svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd""# - .split_ascii_whitespace() - )) + .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.split_ascii_whitespace().eq(known.split_ascii_whitespace()))) } // Check the raster and its end marker before publishing, without storing a full frame. diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs index 3467b3a52..7db81cb5b 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -22,6 +22,7 @@ mod goat; mod graphviz; mod msc; mod pikchr; +pub mod renderer; mod tikz; mod wavedrom_cli; diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs new file mode 100644 index 000000000..1a430853c --- /dev/null +++ b/extensions/diagram/src/renderer.rs @@ -0,0 +1,158 @@ +//! 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)> { + 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, roots.embedded, roots, input) + })?; + let file = file_macro( + self.name, + output, + self.attributes, + move |dir, roots, input| self.render(&tool, dir, roots, input), + )?; + Ok((block, file)) + } + + fn render( + self, + tool: &Path, + 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.extension() == 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| diagram_attribute(input, self.name, 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()]); + image( + self.name, + roots, + input, + format, + identity, + |scratch, output| { + (self.generate)(&Job { + tool, + name: self.tool, + dir, + format, + source: &source, + options: &options, + scratch, + output, + }) + }, + ) + } +} + +struct Job<'a> { + 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 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, +}; From 1323b3f4e3a9759b11082a254a0633b8736e0e98 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:37:56 +0100 Subject: [PATCH 27/60] feat(diagram): render seqdiag blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ acdc-cli/src/subcommands/convert/extensions.rs | 12 +++++++++--- acdc-cli/tests/convert/diagram.rs | 16 ++++++++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 ++++ extensions/diagram/src/renderer.rs | 9 +++++++++ 6 files changed, 42 insertions(+), 3 deletions(-) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 0c39b120c..b78f4fb80 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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`. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 8065e3c0e..837727626 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -72,6 +72,9 @@ 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -106,9 +109,12 @@ impl DiagramArgs { fn configured_renderers( &self, ) -> impl Iterator { - [(acdc_diagram::renderer::BLOCKDIAG, self.blockdiag.as_deref())] - .into_iter() - .filter_map(|(renderer, path): (_, Option<&Path>)| path.map(|p| (renderer, p))) + [ + (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 has_renderer(&self) -> bool { diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 491967da9..f6a78c7a4 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -115,6 +115,22 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index d25c3113e..6cb5d8b99 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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`. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index cad326293..78ea27f3e 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -129,6 +129,10 @@ Library callers register `acdc_diagram::bytefield` and `acdc_diagram::bytefield_ 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 1a430853c..12f952ddf 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -156,3 +156,12 @@ pub const BLOCKDIAG: Renderer = Renderer { 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, +}; From 18b36c2960804f2f718dc43f5e513796a3eb3e68 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:38:30 +0100 Subject: [PATCH 28/60] feat(diagram): render actdiag blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ acdc-cli/src/subcommands/convert/extensions.rs | 4 ++++ acdc-cli/tests/convert/diagram.rs | 16 ++++++++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 ++++ extensions/diagram/src/renderer.rs | 9 +++++++++ 6 files changed, 37 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index b78f4fb80..4b97000e8 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 837727626..7f08f46b4 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -75,6 +75,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -110,6 +113,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (acdc_diagram::renderer::ACTDIAG, self.actdiag.as_deref()), (acdc_diagram::renderer::SEQDIAG, self.seqdiag.as_deref()), (acdc_diagram::renderer::BLOCKDIAG, self.blockdiag.as_deref()), ] diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index f6a78c7a4..1bc79831a 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -131,6 +131,22 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 6cb5d8b99..167f408ee 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 78ea27f3e..45565b4f0 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -133,6 +133,10 @@ Render `[blockdiag]` blocks and `blockdiag::chart.diag[]` files with `--blockdia 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 12f952ddf..4554dc6c4 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -165,3 +165,12 @@ pub const SEQDIAG: Renderer = Renderer { 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, +}; From 9ee97611652a15f3ad21d757849e65651bdce060 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:39:03 +0100 Subject: [PATCH 29/60] feat(diagram): render nwdiag blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ acdc-cli/src/subcommands/convert/extensions.rs | 4 ++++ acdc-cli/tests/convert/diagram.rs | 16 ++++++++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 ++++ extensions/diagram/src/renderer.rs | 9 +++++++++ 6 files changed, 37 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 4b97000e8..63b67b72d 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 7f08f46b4..c97dab059 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -78,6 +78,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -113,6 +116,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (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()), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 1bc79831a..d48c60ffe 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -147,6 +147,22 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 167f408ee..795d52f94 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 45565b4f0..f4e165d46 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -137,6 +137,10 @@ Render `[seqdiag]` blocks and `seqdiag::chart.diag[]` files with `--seqdiag PATH 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 4554dc6c4..391f98bab 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -174,3 +174,12 @@ pub const ACTDIAG: Renderer = Renderer { 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, +}; From c350625824b69c1d0b8490d6c3fddbb364d49cc4 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:39:35 +0100 Subject: [PATCH 30/60] feat(diagram): render packetdiag blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ acdc-cli/src/subcommands/convert/extensions.rs | 7 +++++++ acdc-cli/tests/convert/diagram.rs | 16 ++++++++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 ++++ extensions/diagram/src/renderer.rs | 9 +++++++++ 6 files changed, 40 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 63b67b72d..0cc9585cb 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index c97dab059..e00f20450 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -81,6 +81,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -116,6 +119,10 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + ( + 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()), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index d48c60ffe..c4d675d9f 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -163,6 +163,22 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 795d52f94..01e53e844 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index f4e165d46..9f7627980 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -141,6 +141,10 @@ Render `[actdiag]` blocks and `actdiag::chart.diag[]` files with `--actdiag PATH 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 391f98bab..93574eff1 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -183,3 +183,12 @@ pub const NWDIAG: Renderer = Renderer { 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, +}; From cf796df39984dc5424a403ccf1da6221f4d93935 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:40:13 +0100 Subject: [PATCH 31/60] feat(diagram): render rackdiag blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ acdc-cli/src/subcommands/convert/extensions.rs | 4 ++++ acdc-cli/tests/convert/diagram.rs | 16 ++++++++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 ++++ extensions/diagram/src/renderer.rs | 9 +++++++++ 6 files changed, 37 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 0cc9585cb..d205cc38a 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index e00f20450..dce51d058 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -84,6 +84,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -119,6 +122,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (acdc_diagram::renderer::RACKDIAG, self.rackdiag.as_deref()), ( acdc_diagram::renderer::PACKETDIAG, self.packetdiag.as_deref(), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index c4d675d9f..8ca24b332 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -179,6 +179,22 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 01e53e844..d19757d5b 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 9f7627980..295c65289 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -145,6 +145,10 @@ Render `[nwdiag]` blocks and `nwdiag::chart.diag[]` files with `--nwdiag PATH`. 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 93574eff1..a8cc37339 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -192,3 +192,12 @@ pub const PACKETDIAG: Renderer = Renderer { 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, +}; From 5757bdb54c750d9e46b4629ef0347dfa10ada223 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:40:54 +0100 Subject: [PATCH 32/60] feat(diagram): render nomnoml blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ .../src/subcommands/convert/extensions.rs | 4 ++++ acdc-cli/tests/convert/diagram.rs | 13 +++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 ++++ extensions/diagram/src/renderer.rs | 23 +++++++++++++++++++ 6 files changed, 48 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index d205cc38a..3b00c03b3 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index dce51d058..3396eabc8 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -87,6 +87,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -122,6 +125,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (acdc_diagram::renderer::NOMNOML, self.nomnoml.as_deref()), (acdc_diagram::renderer::RACKDIAG, self.rackdiag.as_deref()), ( acdc_diagram::renderer::PACKETDIAG, diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 8ca24b332..2e35ae168 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -195,6 +195,19 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index d19757d5b..63bfba933 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 295c65289..99824d973 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -149,6 +149,10 @@ Render `[packetdiag]` blocks and `packetdiag::chart.diag[]` files with `--packet 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index a8cc37339..6cca5c962 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -124,6 +124,15 @@ struct Job<'a> { } impl Job<'_> { + 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() @@ -201,3 +210,17 @@ pub const RACKDIAG: Renderer = Renderer { 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, +}; From 0211ba689995fbb46f3302d1ddd0d10ab6eb8c70 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:41:30 +0100 Subject: [PATCH 33/60] feat(diagram): render smcat blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ .../src/subcommands/convert/extensions.rs | 4 +++ acdc-cli/tests/convert/diagram.rs | 13 ++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 +++ extensions/diagram/src/renderer.rs | 26 +++++++++++++++++++ 6 files changed, 51 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 3b00c03b3..aa736d358 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 3396eabc8..b977c0758 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -90,6 +90,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -125,6 +128,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (acdc_diagram::renderer::SMCAT, self.smcat.as_deref()), (acdc_diagram::renderer::NOMNOML, self.nomnoml.as_deref()), (acdc_diagram::renderer::RACKDIAG, self.rackdiag.as_deref()), ( diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 2e35ae168..7a1abae1f 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -208,6 +208,19 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 63bfba933..d15c46112 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 99824d973..3129d747c 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -153,6 +153,10 @@ Render `[rackdiag]` blocks and `rackdiag::chart.diag[]` files with `--rackdiag P 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 6cca5c962..7e007f78e 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -124,6 +124,14 @@ struct Job<'a> { } impl Job<'_> { + 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)?; @@ -224,3 +232,21 @@ pub const NOMNOML: Renderer = Renderer { 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, +}; From 6f04ef0b230d2c70a2b7cb4e008be54e8b2e06ca Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:42:04 +0100 Subject: [PATCH 34/60] feat(diagram): render dbml blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ acdc-cli/src/subcommands/convert/extensions.rs | 4 ++++ acdc-cli/tests/convert/diagram.rs | 13 +++++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 ++++ extensions/diagram/src/renderer.rs | 13 +++++++++++++ 6 files changed, 38 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index aa736d358..ba026c7c8 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index b977c0758..0efab8501 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -93,6 +93,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -128,6 +131,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (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()), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 7a1abae1f..d09fc195b 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -221,6 +221,19 @@ printf '%s' '' > ) } + #[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' '' "#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index d15c46112..f2665af6e 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 3129d747c..5195900a7 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -157,6 +157,10 @@ Render `[nomnoml]` blocks and `nomnoml::chart.nomnoml[]` files with `--nomnoml P 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 7e007f78e..f45ea0f6e 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -250,3 +250,16 @@ pub const SMCAT: Renderer = Renderer { 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, +}; From c339cd6071e6b6076b92e5c46839f869af0866a3 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:42:38 +0100 Subject: [PATCH 35/60] feat(diagram): render graphviz_py blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ .../src/subcommands/convert/extensions.rs | 7 +++++++ acdc-cli/tests/convert/diagram.rs | 13 ++++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 ++++ extensions/diagram/src/renderer.rs | 21 +++++++++++++++++++ 6 files changed, 49 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index ba026c7c8..2d5c20f70 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 0efab8501..b5c4193d6 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -96,6 +96,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -131,6 +134,10 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + ( + 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()), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index d09fc195b..b38895bda 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -234,6 +234,19 @@ 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}""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index f2665af6e..18ade2f2c 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 5195900a7..eba96e207 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -161,6 +161,10 @@ Render `[smcat]` blocks and `smcat::chart.smcat[]` files with `--smcat PATH`. Se 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index f45ea0f6e..523a7a319 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -263,3 +263,24 @@ pub const DBML: Renderer = Renderer { 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, +}; From 695affc8dedf2ef2e9e63da21d4027c5368ff61d Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:43:17 +0100 Subject: [PATCH 36/60] feat(diagram): render d2 blocks and file macros --- acdc-cli/CHANGELOG.md | 2 + .../src/subcommands/convert/extensions.rs | 4 ++ acdc-cli/tests/convert/diagram.rs | 13 ++++++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 4 ++ extensions/diagram/src/renderer.rs | 42 +++++++++++++++++++ 6 files changed, 67 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 2d5c20f70..ec02a70f9 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index b5c4193d6..cacc73808 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -99,6 +99,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -134,6 +137,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (acdc_diagram::renderer::D2, self.d2.as_deref()), ( acdc_diagram::renderer::GRAPHVIZ_PY, self.graphviz_py.as_deref(), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index b38895bda..2f8094199 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -247,6 +247,19 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 18ade2f2c..ab9564e7b 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index eba96e207..320a8c21b 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -165,6 +165,10 @@ Render `[dbml]` blocks and `dbml::chart.dbml[]` files with `--dbml-renderer PATH 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 523a7a319..994475eb9 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -284,3 +284,45 @@ pub const GRAPHVIZ_PY: Renderer = Renderer { 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, +}; From 53ddf26a1929157f0ee4125c352812233729d9d2 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:44:07 +0100 Subject: [PATCH 37/60] feat(diagram): render shaape blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ .../src/subcommands/convert/extensions.rs | 4 ++++ acdc-cli/tests/convert/diagram.rs | 13 +++++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 ++++ extensions/diagram/src/renderer.rs | 19 +++++++++++++++++++ 6 files changed, 44 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index ec02a70f9..c0906afc0 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index cacc73808..95b8ac29a 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -102,6 +102,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -137,6 +140,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (acdc_diagram::renderer::SHAAPE, self.shaape.as_deref()), (acdc_diagram::renderer::D2, self.d2.as_deref()), ( acdc_diagram::renderer::GRAPHVIZ_PY, diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 2f8094199..e90c0e23d 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -260,6 +260,19 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index ab9564e7b..523e4a150 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 320a8c21b..6a5c4fd65 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -169,6 +169,10 @@ Render `[graphviz_py]` blocks and `graphviz_py::chart.dot[]` files with `--graph 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 994475eb9..04f6ce9e3 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -326,3 +326,22 @@ pub const D2: Renderer = Renderer { ], 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, +}; From d52272a754ea1f3ecc271cd6b88765b1155518df Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:44:44 +0100 Subject: [PATCH 38/60] feat(diagram): render symbolator blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ .../src/subcommands/convert/extensions.rs | 7 +++++++ acdc-cli/tests/convert/diagram.rs | 13 ++++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 ++++ extensions/diagram/src/renderer.rs | 21 +++++++++++++++++++ 6 files changed, 49 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index c0906afc0..1c20a74e3 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 95b8ac29a..f3dfc9814 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -105,6 +105,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -140,6 +143,10 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + ( + acdc_diagram::renderer::SYMBOLATOR, + self.symbolator.as_deref(), + ), (acdc_diagram::renderer::SHAAPE, self.shaape.as_deref()), (acdc_diagram::renderer::D2, self.d2.as_deref()), ( diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index e90c0e23d..f12373429 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -273,6 +273,19 @@ printf '%s' '' > ) } + #[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}""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 523e4a150..032eca47e 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 6a5c4fd65..a379daa55 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -173,6 +173,10 @@ Render `[d2]` blocks and `d2::chart.d2[]` files with `--d2 PATH`. SVG is the def 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 04f6ce9e3..6dd9d84ef 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -345,3 +345,24 @@ pub const SHAAPE: Renderer = Renderer { 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, +}; From 1e5da64e703e63db2ff89a6e6483d3b662b5b0ad Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:45:25 +0100 Subject: [PATCH 39/60] feat(diagram): render pintora blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ .../src/subcommands/convert/extensions.rs | 4 +++ acdc-cli/tests/convert/diagram.rs | 13 +++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 +++ extensions/diagram/src/renderer.rs | 28 +++++++++++++++++++ 6 files changed, 53 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 1c20a74e3..62fef3380 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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`. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index f3dfc9814..f4dc11a95 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -108,6 +108,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -143,6 +146,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (acdc_diagram::renderer::PINTORA, self.pintora.as_deref()), ( acdc_diagram::renderer::SYMBOLATOR, self.symbolator.as_deref(), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index f12373429..21713c0fa 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -286,6 +286,19 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 032eca47e..3d4dda20b 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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`. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index a379daa55..825e617a0 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -177,6 +177,10 @@ Render `[shaape]` blocks and `shaape::chart.shaape[]` files with `--shaape PATH` 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 6dd9d84ef..c6ad1118b 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -366,3 +366,31 @@ pub const SYMBOLATOR: Renderer = Renderer { 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, +}; From ce10e176d13183122f64f10285b51729efc7ebdd Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:47:22 +0100 Subject: [PATCH 40/60] feat(diagram): render a2s blocks and file macros --- acdc-cli/CHANGELOG.md | 2 + .../src/subcommands/convert/extensions.rs | 4 ++ acdc-cli/tests/convert/diagram.rs | 13 ++++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 4 ++ extensions/diagram/src/asset.rs | 40 ++++++++--- extensions/diagram/src/graphviz.rs | 1 + extensions/diagram/src/lib.rs | 16 +++-- extensions/diagram/src/msc.rs | 1 + extensions/diagram/src/renderer.rs | 72 +++++++++++++++---- extensions/diagram/src/tikz.rs | 50 +++++++------ 11 files changed, 159 insertions(+), 46 deletions(-) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 62fef3380..e35f43f07 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index f4dc11a95..53a36bc7c 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -111,6 +111,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -146,6 +149,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (acdc_diagram::renderer::A2S, self.a2s.as_deref()), (acdc_diagram::renderer::PINTORA, self.pintora.as_deref()), ( acdc_diagram::renderer::SYMBOLATOR, diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 21713c0fa..0aa1e6b9a 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -299,6 +299,19 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 3d4dda20b..6ed1059c8 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 825e617a0..ea925e5fd 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -181,6 +181,10 @@ Render `[symbolator]` blocks and `symbolator::chart.vhd[]` files with `--symbola 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`. + == 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. diff --git a/extensions/diagram/src/asset.rs b/extensions/diagram/src/asset.rs index 4a96aec9e..a4982f072 100644 --- a/extensions/diagram/src/asset.rs +++ b/extensions/diagram/src/asset.rs @@ -8,7 +8,7 @@ use std::{ use svgtypes::{Length, LengthUnit, ViewBox}; -const MAX_BYTES: u64 = 16 * 1024 * 1024; +pub(super) const MAX_BYTES: u64 = 16 * 1024 * 1024; pub(super) struct ImageSize { pub(super) width: f64, @@ -45,6 +45,7 @@ impl ImageSize { #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum Format { + Txt, Svg, Png, Pdf, @@ -53,6 +54,7 @@ pub(super) enum Format { impl Format { pub(super) fn extension(self) -> &'static str { match self { + Self::Txt => "txt", Self::Svg => "svg", Self::Png => "png", Self::Pdf => "pdf", @@ -68,6 +70,7 @@ impl Format { } let mut file = fs::File::open(path)?; match self { + Self::Txt => Err(io::Error::other("text output requires a literal block")), Self::Svg => { let mut svg = String::new(); file.take(MAX_BYTES + 1).read_to_string(&mut svg)?; @@ -148,12 +151,7 @@ fn validate_png(file: fs::File) -> io::Result { }) } -pub(super) fn publish( - dir: &Path, - filename: &str, - format: Format, - generate: impl FnOnce(&Path, &Path) -> io::Result<()>, -) -> io::Result> { +pub(super) fn scratch_dir(dir: &Path) -> io::Result { let mut scratch = tempfile::Builder::new(); scratch.prefix(".acdc-diagram-"); #[cfg(unix)] @@ -161,7 +159,33 @@ pub(super) fn publish( use std::os::unix::fs::PermissionsExt as _; scratch.permissions(fs::Permissions::from_mode(0o700)); } - let scratch = scratch.tempdir_in(dir)?; + 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())); diff --git a/extensions/diagram/src/graphviz.rs b/extensions/diagram/src/graphviz.rs index 80e60165e..224e6d6ac 100644 --- a/extensions/diagram/src/graphviz.rs +++ b/extensions/diagram/src/graphviz.rs @@ -84,6 +84,7 @@ fn render( input, format, [layout.unwrap_or_default(), "\0", source.as_ref()], + false, |scratch, output| { let mut cmd = Command::new(dot); cmd.arg("-o") diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs index 7db81cb5b..7261189e2 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -287,6 +287,7 @@ fn render( input, format, [source.as_ref()], + false, |scratch, output| wavedrom_cli::render(tool, &source, format, scratch, output), ) } @@ -349,6 +350,7 @@ fn render_svg( .iter() .flat_map(|arg| [*arg, "\0"]) .chain([source.as_ref()]), + false, |scratch, output| generate(&source, scratch, output), ) } @@ -390,6 +392,7 @@ fn image<'a>( input: &DiagramInput<'_>, format: Format, identity: impl IntoIterator, + native_scale: bool, generate: impl FnOnce(&Path, &Path) -> io::Result<()>, ) -> Result { let attrs = input.document_attributes; @@ -463,11 +466,14 @@ fn image<'a>( if backend.starts_with("html") && let Some(size) = size { - let scale = args - .get_string("scale") - .and_then(|value| value.parse::().ok()) - .filter(|scale| scale.is_finite() && *scale >= 0.0) - .unwrap_or(1.0); + 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() { diff --git a/extensions/diagram/src/msc.rs b/extensions/diagram/src/msc.rs index efec237d3..16cf4111c 100644 --- a/extensions/diagram/src/msc.rs +++ b/extensions/diagram/src/msc.rs @@ -78,6 +78,7 @@ fn render( 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()); diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index c6ad1118b..a0b35c09b 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -90,24 +90,37 @@ impl Renderer { .iter() .flat_map(|(k, v)| [*k, "\0", v.as_ref(), "\0"]) .chain([source.as_ref()]); + let generate = |scratch: &Path, output: &Path| { + (self.generate)(&Job { + tool, + name: self.tool, + dir, + format, + source: &source, + options: &options, + scratch, + output, + }) + }; + if format == Format::Txt { + 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, - |scratch, output| { - (self.generate)(&Job { - tool, - name: self.tool, - dir, - format, - source: &source, - options: &options, - scratch, - output, - }) - }, + self.attributes.contains(&"scale"), + generate, ) } } @@ -394,3 +407,38 @@ pub const PINTORA: Renderer = Renderer { 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, +}; diff --git a/extensions/diagram/src/tikz.rs b/extensions/diagram/src/tikz.rs index a595089b3..6636c6bc1 100644 --- a/extensions/diagram/src/tikz.rs +++ b/extensions/diagram/src/tikz.rs @@ -85,27 +85,35 @@ pub fn tikz<'a>( .any(|opt| *opt == "preamble"); let document = latex_document(&diagram_source(input), preamble); let identity = [document.as_str()]; - image("tikz", root, input, format, identity, |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) - } - }) + 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) + } + }, + ) }) } From 5a0fbbcf95562830e509223adf85c56f43631a82 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:47:55 +0100 Subject: [PATCH 41/60] feat(diagram): render svgbob blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ .../src/subcommands/convert/extensions.rs | 4 +++ acdc-cli/tests/convert/diagram.rs | 13 +++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 +++ extensions/diagram/src/renderer.rs | 27 +++++++++++++++++++ 6 files changed, 52 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index e35f43f07..970b0a71d 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 53a36bc7c..3cf3711c1 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -114,6 +114,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -149,6 +152,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (acdc_diagram::renderer::SVGBOB, self.svgbob.as_deref()), (acdc_diagram::renderer::A2S, self.a2s.as_deref()), (acdc_diagram::renderer::PINTORA, self.pintora.as_deref()), ( diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 0aa1e6b9a..df39c293f 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -312,6 +312,19 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 6ed1059c8..a9640500e 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index ea925e5fd..022db87b9 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -185,6 +185,10 @@ Render `[pintora]` blocks and `pintora::chart.pintora[]` files with `--pintora P 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index a0b35c09b..cd982b746 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -442,3 +442,30 @@ pub const A2S: Renderer = Renderer { 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, +}; From 9080c7ae0e9a371333846c08ac302fa4f222cc5e Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:48:37 +0100 Subject: [PATCH 42/60] feat(diagram): render syntrax blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ .../src/subcommands/convert/extensions.rs | 4 +++ acdc-cli/tests/convert/diagram.rs | 13 +++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 +++ extensions/diagram/src/renderer.rs | 27 +++++++++++++++++++ 6 files changed, 52 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 970b0a71d..7a8dce3e5 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 3cf3711c1..a06024f7a 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -117,6 +117,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -152,6 +155,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (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()), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index df39c293f..753cf9ef8 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -325,6 +325,19 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index a9640500e..a69be5556 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 022db87b9..7612251ee 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -189,6 +189,10 @@ Render `[a2s]` blocks and `a2s::chart.txt[]` files with `--a2s PATH`. SVG is the 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index cd982b746..27ac61fc4 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -469,3 +469,30 @@ pub const SVGBOB: Renderer = Renderer { 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, +}; From 0a7ea8adb309e7ed333038a3a35584e17cea8428 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:49:11 +0100 Subject: [PATCH 43/60] feat(diagram): render diagrams blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ .../src/subcommands/convert/extensions.rs | 7 ++++ acdc-cli/tests/convert/diagram.rs | 13 ++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 +++ extensions/diagram/src/renderer.rs | 33 +++++++++++++++++++ 6 files changed, 61 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 7a8dce3e5..b27ba6559 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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`. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index a06024f7a..5aba126b5 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -120,6 +120,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -155,6 +158,10 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + ( + 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()), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 753cf9ef8..7253de667 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -338,6 +338,19 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index a69be5556..3050d9ba4 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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`. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 7612251ee..c991e799f 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -193,6 +193,10 @@ Render `[svgbob]` blocks and `svgbob::chart.bob[]` files with `--svgbob PATH`. C 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 27ac61fc4..916630911 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -496,3 +496,36 @@ pub const SYNTRAX: Renderer = Renderer { 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, +}; From 240bcf5eb44d4ebe96d15554ba487e1a502dafda Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:50:53 +0100 Subject: [PATCH 44/60] feat(diagram): render ditaa blocks and file macros --- acdc-cli/CHANGELOG.md | 2 + .../src/subcommands/convert/extensions.rs | 4 ++ acdc-cli/tests/convert/diagram.rs | 13 +++++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 4 ++ extensions/diagram/src/renderer.rs | 56 +++++++++++++++++++ 6 files changed, 81 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index b27ba6559..16761d399 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 5aba126b5..9805a2ab6 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -123,6 +123,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -158,6 +161,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (acdc_diagram::renderer::DITAA, self.ditaa.as_deref()), ( acdc_diagram::renderer::DIAGRAMS, self.diagrams_python.as_deref(), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 7253de667..2e08b5d04 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -351,6 +351,19 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 3050d9ba4..15db2fdd2 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index c991e799f..9c9e8358c 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -197,6 +197,10 @@ Render `[syntrax]` blocks and `syntrax::chart.spec[]` files with `--syntrax PATH 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 916630911..b5968cd4d 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -529,3 +529,59 @@ pub const DIAGRAMS: Renderer = Renderer { 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, +}; From 1d0a758837cb3ca7aec533cb01c5068cd50ec72a Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:51:33 +0100 Subject: [PATCH 45/60] feat(diagram): render tape blocks and file macros --- Cargo.lock | 1 + acdc-cli/CHANGELOG.md | 2 ++ acdc-cli/src/subcommands/convert/extensions.rs | 4 ++++ acdc-cli/tests/convert/diagram.rs | 13 +++++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/Cargo.toml | 1 + extensions/diagram/README.adoc | 4 ++++ extensions/diagram/src/asset.rs | 15 +++++++++++++++ extensions/diagram/src/renderer.rs | 14 ++++++++++++++ 9 files changed, 56 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 6b8e5c6a6..2a17a0db5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -162,6 +162,7 @@ dependencies = [ "acdc-converters-html", "acdc-parser", "base64 0.23.1", + "image", "lopdf", "png", "roxmltree 0.21.1", diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 16761d399..30bfe9dac 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 9805a2ab6..283616eb6 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -126,6 +126,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -161,6 +164,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (acdc_diagram::renderer::TAPE, self.vhs.as_deref()), (acdc_diagram::renderer::DITAA, self.ditaa.as_deref()), ( acdc_diagram::renderer::DIAGRAMS, diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 2e08b5d04..37e64b975 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -364,6 +364,19 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 15db2fdd2..e0396ac41 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/Cargo.toml b/extensions/diagram/Cargo.toml index 93018bac3..96123e30d 100644 --- a/extensions/diagram/Cargo.toml +++ b/extensions/diagram/Cargo.toml @@ -9,6 +9,7 @@ publish = false [dependencies] acdc-parser.workspace = true +image.workspace = true png = "0.18" roxmltree = "0.21" base64.workspace = true diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 9c9e8358c..28fc379b8 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -201,6 +201,10 @@ Render `[diagrams]` blocks and `diagrams::chart.py[]` files with `--diagrams-pyt 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. Use `format=svg` for an SVG recording. Tape scripts run in unsafe mode. Enable the package with `--extension 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. diff --git a/extensions/diagram/src/asset.rs b/extensions/diagram/src/asset.rs index a4982f072..6209a739e 100644 --- a/extensions/diagram/src/asset.rs +++ b/extensions/diagram/src/asset.rs @@ -46,6 +46,7 @@ impl ImageSize { #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum Format { Txt, + Gif, Svg, Png, Pdf, @@ -55,6 +56,7 @@ impl Format { pub(super) fn extension(self) -> &'static str { match self { Self::Txt => "txt", + Self::Gif => "gif", Self::Svg => "svg", Self::Png => "png", Self::Pdf => "pdf", @@ -71,6 +73,7 @@ impl Format { let mut file = fs::File::open(path)?; match self { Self::Txt => Err(io::Error::other("text output requires a literal block")), + Self::Gif => validate_raster(file, image::ImageFormat::Gif).map(Some), Self::Svg => { let mut svg = String::new(); file.take(MAX_BYTES + 1).read_to_string(&mut svg)?; @@ -124,6 +127,18 @@ fn declares_standard_svg(svg: &str) -> bool { } // 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( diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index b5968cd4d..bc54f0f5e 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -585,3 +585,17 @@ pub const DITAA: Renderer = Renderer { ], 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, +}; From e4d9c1b23ddb4d67d5dce3ab6485ff52ef306aa1 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:52:08 +0100 Subject: [PATCH 46/60] feat(diagram): render gnuplot blocks and file macros --- acdc-cli/CHANGELOG.md | 2 + .../src/subcommands/convert/extensions.rs | 4 ++ acdc-cli/tests/convert/diagram.rs | 13 +++++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 4 ++ extensions/diagram/src/renderer.rs | 56 +++++++++++++++++++ 6 files changed, 81 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 30bfe9dac..115c5995a 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 283616eb6..8f12605e7 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -129,6 +129,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -164,6 +167,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (acdc_diagram::renderer::GNUPLOT, self.gnuplot.as_deref()), (acdc_diagram::renderer::TAPE, self.vhs.as_deref()), (acdc_diagram::renderer::DITAA, self.ditaa.as_deref()), ( diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 37e64b975..3db964d9d 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -377,6 +377,19 @@ printf '%s' '' > ) } + #[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' '' "#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index e0396ac41..cc399b627 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 28fc379b8..22e388822 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -205,6 +205,10 @@ Render `[ditaa]` blocks and `ditaa::chart.ditaa[]` files with `--ditaa PATH`. Ch 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. 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index bc54f0f5e..b532c6d0e 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -599,3 +599,59 @@ pub const TAPE: Renderer = Renderer { 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, +}; From 197e926d3b73098981bd3a99ae157ea0a1095fdc Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:52:42 +0100 Subject: [PATCH 47/60] feat(diagram): render umlet blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ .../src/subcommands/convert/extensions.rs | 4 ++++ acdc-cli/tests/convert/diagram.rs | 13 ++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 ++++ extensions/diagram/src/renderer.rs | 24 +++++++++++++++++++ 6 files changed, 49 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 115c5995a..0b69d13fa 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- Render `[umlet]` blocks and `umlet::chart.uxf[]` files with `--umlet PATH`. Choose SVG (default), PNG, PDF, or GIF using a UMLet command-line launcher. + - 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 8f12605e7..0cff53902 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -132,6 +132,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -167,6 +170,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (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()), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 3db964d9d..6a38826e2 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -390,6 +390,19 @@ 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' '' > "${4#-output=}""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index cc399b627..e8778c381 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- Render `[umlet]` blocks and `umlet::chart.uxf[]` files with `--umlet PATH`. Choose SVG (default), PNG, PDF, or GIF using a UMLet command-line launcher. + - 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 22e388822..49bd313f7 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -209,6 +209,10 @@ Render `[tape]` blocks and `tape::chart.tape[]` files with `--vhs PATH`. GIF is 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index b532c6d0e..1e7c93266 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -655,3 +655,27 @@ pub const GNUPLOT: Renderer = Renderer { ], 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, +}; From ad4d9bf8f35ab41e39e8fd1f32fb6fd3c1e79023 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:55:09 +0100 Subject: [PATCH 48/60] feat(diagram): render bpmn blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ .../src/subcommands/convert/extensions.rs | 4 ++++ acdc-cli/tests/convert/diagram.rs | 13 ++++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 ++++ extensions/diagram/src/asset.rs | 11 +++++++++- extensions/diagram/src/renderer.rs | 20 +++++++++++++++++++ 7 files changed, 55 insertions(+), 1 deletion(-) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 0b69d13fa..afef0f962 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. - 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 0cff53902..c08b57f71 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -135,6 +135,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -170,6 +173,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (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()), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 6a38826e2..47279769c 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -403,6 +403,19 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index e8778c381..98dd896cd 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. - 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 49bd313f7..620d33bca 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -213,6 +213,10 @@ Render `[gnuplot]` blocks and `gnuplot::chart.gp[]` files with `--gnuplot PATH`. 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`. + == 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. diff --git a/extensions/diagram/src/asset.rs b/extensions/diagram/src/asset.rs index 6209a739e..aa4e928f5 100644 --- a/extensions/diagram/src/asset.rs +++ b/extensions/diagram/src/asset.rs @@ -47,6 +47,7 @@ impl ImageSize { pub(super) enum Format { Txt, Gif, + Jpeg, Svg, Png, Pdf, @@ -57,6 +58,7 @@ impl Format { match self { Self::Txt => "txt", Self::Gif => "gif", + Self::Jpeg => "jpeg", Self::Svg => "svg", Self::Png => "png", Self::Pdf => "pdf", @@ -74,6 +76,7 @@ impl Format { match self { Self::Txt => 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)?; @@ -114,10 +117,16 @@ impl Format { // 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 prolog = svg + 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, _)| [ diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 1e7c93266..181d21155 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -679,3 +679,23 @@ pub const UMLET: Renderer = Renderer { 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, +}; From 6c61d159b1f8d092c7caa7cedce197080eb89c26 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:56:38 +0100 Subject: [PATCH 49/60] feat(diagram): render mermaid blocks and file macros --- acdc-cli/CHANGELOG.md | 2 + .../src/subcommands/convert/extensions.rs | 4 ++ acdc-cli/tests/convert/diagram.rs | 13 +++++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 4 ++ extensions/diagram/src/renderer.rs | 25 +++++++++ extensions/diagram/src/renderer/mermaid.rs | 55 +++++++++++++++++++ 7 files changed, 105 insertions(+) create mode 100644 extensions/diagram/src/renderer/mermaid.rs diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index afef0f962..f6a14dac6 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index c08b57f71..193f6e897 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -138,6 +138,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -173,6 +176,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (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()), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 47279769c..4e6baa8ce 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -416,6 +416,19 @@ printf '%s' ' 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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 98dd896cd..35a1a1f8a 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 620d33bca..311ef60ce 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -217,6 +217,10 @@ Render `[umlet]` blocks and `umlet::chart.uxf[]` files with `--umlet PATH`. Choo 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. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 181d21155..358646e57 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -699,3 +699,28 @@ pub const BPMN: Renderer = Renderer { 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, +}; 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")) +} From 36779fec703c250a17b8609b8feaca8b57e0b227 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:57:14 +0100 Subject: [PATCH 50/60] feat(diagram): render oxdraw blocks and file macros --- acdc-cli/CHANGELOG.md | 2 + .../src/subcommands/convert/extensions.rs | 4 ++ acdc-cli/tests/convert/diagram.rs | 13 ++++++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 4 ++ extensions/diagram/src/renderer.rs | 11 +++++ extensions/diagram/src/renderer/oxdraw.rs | 42 +++++++++++++++++++ 7 files changed, 78 insertions(+) create mode 100644 extensions/diagram/src/renderer/oxdraw.rs diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index f6a14dac6..730ab0bd9 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 193f6e897..11ede3382 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -141,6 +141,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -176,6 +179,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (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()), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 4e6baa8ce..fb6de020b 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -429,6 +429,19 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 35a1a1f8a..5f75e2864 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 311ef60ce..2b89c781a 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -221,6 +221,10 @@ Render `[bpmn]` blocks and `bpmn::chart.bpmn[]` files with `--bpmn-js PATH`. Cho 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 358646e57..16cf5b367 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -724,3 +724,14 @@ pub const MERMAID: Renderer = Renderer { ], 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, +}; diff --git a/extensions/diagram/src/renderer/oxdraw.rs b/extensions/diagram/src/renderer/oxdraw.rs new file mode 100644 index 000000000..78c10b26e --- /dev/null +++ b/extensions/diagram/src/renderer/oxdraw.rs @@ -0,0 +1,42 @@ +use super::Job; +use crate::asset; +use crate::asset::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(()) +} From fd629ba78a553bbd0c4801336d27f692aed3deda Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:57:52 +0100 Subject: [PATCH 51/60] feat(diagram): render lilypond blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ .../src/subcommands/convert/extensions.rs | 4 +++ acdc-cli/tests/convert/diagram.rs | 15 ++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 +++ extensions/diagram/src/renderer.rs | 34 +++++++++++++++++++ 6 files changed, 61 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 730ab0bd9..1ff6122bc 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 11ede3382..c383beb4d 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -144,6 +144,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -179,6 +182,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (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()), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index fb6de020b..5787da589 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -442,6 +442,21 @@ printf '%s' '' > ) } + #[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""#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 5f75e2864..7606d7fbb 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 2b89c781a..6e566fcb6 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -225,6 +225,10 @@ Render `[mermaid]` blocks and `mermaid::chart.mmd[]` files with `--mmdc PATH`. C 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 16cf5b367..7b53c6651 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -735,3 +735,37 @@ pub const OXDRAW: Renderer = Renderer { 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, +}; From 9095c526d919d3ba3c8085dd7547e8433221fc2a Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:58:47 +0100 Subject: [PATCH 52/60] fix(diagram): accept UMLet SVG public identifiers in single quotes --- acdc-cli/CHANGELOG.md | 2 +- acdc-cli/tests/convert/diagram.rs | 3 ++- extensions/diagram/CHANGELOG.md | 2 +- extensions/diagram/src/asset.rs | 2 +- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 1ff6122bc..884e32e79 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -15,7 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - 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. +- 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. diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 5787da589..2a8b46fef 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -399,7 +399,8 @@ printf '%s' '' "# "svg", r#"test "$1:$2" = "-action=convert:-format=svg" test "$(cat "${3#-filename=}")" = "$(cat chart.source)" -printf '%s' '' > "${4#-output=}""#, +printf '%s\n' "" > "${4#-output=}" +printf '%s' '' >> "${4#-output=}""#, ) } diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 7606d7fbb..06dee60ef 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -10,7 +10,7 @@ - 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. +- 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. diff --git a/extensions/diagram/src/asset.rs b/extensions/diagram/src/asset.rs index aa4e928f5..2f0932c2a 100644 --- a/extensions/diagram/src/asset.rs +++ b/extensions/diagram/src/asset.rs @@ -132,7 +132,7 @@ fn declares_standard_svg(svg: &str) -> bool { .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.split_ascii_whitespace().eq(known.split_ascii_whitespace()))) + ].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. From e623a9c9dbba77633a1fec16441263317043772d Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 21:59:25 +0100 Subject: [PATCH 53/60] feat(diagram): render erd blocks and file macros --- acdc-cli/CHANGELOG.md | 2 + .../src/subcommands/convert/extensions.rs | 10 ++- acdc-cli/tests/convert/diagram.rs | 63 ++++++++++++---- extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 4 ++ extensions/diagram/src/renderer.rs | 71 ++++++++++++++++++- 6 files changed, 135 insertions(+), 17 deletions(-) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 884e32e79..ad0114d90 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index c383beb4d..df2a4b73a 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -147,6 +147,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -182,6 +185,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (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()), @@ -376,9 +380,13 @@ impl DiagramArgs { .register_block_style(style) .map_err(|e| error::display(&e))?; } + let companions: Vec<_> = [("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(tool, output) + .processors_with_tools(tool, output, &companions) .map_err(|e| miette::miette!("cannot configure {}: {e}", tool.display()))?; registry .register_block_style(style) diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 2a8b46fef..edec36fb0 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -458,12 +458,45 @@ printf '%%PDF-1.7 ) } + #[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}""#, + )], + ) + } + 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(); @@ -471,7 +504,7 @@ printf '%%PDF-1.7 fs::write( root.join("doc.adoc"), format!( - "[{style},example,{format}]\n----\n{body}\n----\n\n.File\n{style}::chart.source[{format},alt=Chart]" + "{header}\n[{style},example,{format}]\n----\n{body}\n----\n\n.File\n{style}::chart.source[{format},alt=Chart]" ), )?; fs::write( @@ -479,19 +512,21 @@ printf '%%PDF-1.7 format!("#!/bin/sh\nset -eu\n{renderer}\n"), )?; fs::set_permissions(root.join("renderer"), fs::Permissions::from_mode(0o700))?; - let run = run_acdc_in( - root, - &[ - "convert", - "--extension", - "diagram", - flag, - "./renderer", - "--fail-on-warnings", - "doc.adoc", - ], - None, - )?; + 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"] { diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 06dee60ef..7c1b8f148 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 6e566fcb6..5c4f7eb89 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -229,6 +229,10 @@ Render `[oxdraw]` blocks and `oxdraw::chart.mmd[]` files with `--oxdraw PATH`. S 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 7b53c6651..7f5a881ef 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -28,17 +28,35 @@ impl Renderer { 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, roots.embedded, 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, dir, roots, input), + move |dir, roots, input| self.render(&tool, &companions, dir, roots, input), )?; Ok((block, file)) } @@ -46,6 +64,7 @@ impl Renderer { fn render( self, tool: &Path, + companions: &[(&str, std::path::PathBuf)], dir: &Path, roots: OutputDirectories<'_>, input: &DiagramInput<'_>, @@ -92,6 +111,7 @@ impl Renderer { .chain([source.as_ref()]); let generate = |scratch: &Path, output: &Path| { (self.generate)(&Job { + companions, tool, name: self.tool, dir, @@ -126,6 +146,7 @@ impl Renderer { } struct Job<'a> { + companions: &'a [(&'a str, std::path::PathBuf)], tool: &'a Path, name: &'static str, dir: &'a Path, @@ -137,6 +158,18 @@ struct Job<'a> { } 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) { @@ -769,3 +802,37 @@ pub const LILYPOND: Renderer = Renderer { 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, +}; From 47b6ea402dedf809d5734d463f26d559e30674fc Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 22:00:02 +0100 Subject: [PATCH 54/60] feat(diagram): render penrose blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ .../src/subcommands/convert/extensions.rs | 4 +++ acdc-cli/tests/convert/diagram.rs | 15 ++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 +++ extensions/diagram/src/renderer.rs | 29 +++++++++++++++++++ 6 files changed, 56 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index ad0114d90..dd5db0dd0 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index df2a4b73a..e3ab1169e 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -150,6 +150,9 @@ pub(super) struct DiagramArgs { /// 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 bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -185,6 +188,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (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()), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index edec36fb0..316692a74 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -479,6 +479,21 @@ printf '%s' '' > ) } + #[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", + &[], + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 7c1b8f148..807429190 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 5c4f7eb89..9fb4c750c 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -233,6 +233,10 @@ Render `[lilypond]` blocks and `lilypond::chart.ly[]` files with `--lilypond PAT 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 7f5a881ef..a79b6d63d 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -836,3 +836,32 @@ pub const ERD: Renderer = Renderer { 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, +}; From bb5153e80ac8bf61a0d838393817fc12ad79f2e1 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 22:02:03 +0100 Subject: [PATCH 55/60] feat(diagram): render plantuml blocks and file macros --- acdc-cli/CHANGELOG.md | 2 + .../src/subcommands/convert/extensions.rs | 4 + acdc-cli/tests/convert/diagram.rs | 12 +++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 4 + extensions/diagram/src/asset.rs | 8 +- extensions/diagram/src/renderer.rs | 29 +++++- extensions/diagram/src/renderer/plantuml.rs | 88 +++++++++++++++++++ 8 files changed, 147 insertions(+), 2 deletions(-) create mode 100644 extensions/diagram/src/renderer/plantuml.rs diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index dd5db0dd0..3a851d86d 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index e3ab1169e..f443e9226 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -153,6 +153,9 @@ pub(super) struct DiagramArgs { /// 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, /// Path to the trusted bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -188,6 +191,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (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()), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 316692a74..252db4627 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -494,6 +494,18 @@ printf '%s' '' > ) } + #[test] + fn plantuml_block_and_file() -> TestResult { + tool_sample( + "plantuml", + "--plantuml", + "Alice -> Bob: hello", + "svg", + r#"grep -F '@startuml' >/dev/null +printf '%s' '' "#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 807429190..119f1f8a2 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 9fb4c750c..eb22fd6d8 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -237,6 +237,10 @@ Render `[erd]` blocks and `erd::chart.erd[]` files with `--erd PATH`. Configure 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`. + == 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. diff --git a/extensions/diagram/src/asset.rs b/extensions/diagram/src/asset.rs index 2f0932c2a..c5c77bc32 100644 --- a/extensions/diagram/src/asset.rs +++ b/extensions/diagram/src/asset.rs @@ -45,6 +45,8 @@ impl ImageSize { #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum Format { + Atxt, + Utxt, Txt, Gif, Jpeg, @@ -56,6 +58,8 @@ pub(super) enum Format { 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", @@ -74,7 +78,9 @@ impl Format { } let mut file = fs::File::open(path)?; match self { - Self::Txt => Err(io::Error::other("text output requires a literal block")), + 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 => { diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index a79b6d63d..1d2c817bc 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -111,6 +111,7 @@ impl Renderer { .chain([source.as_ref()]); let generate = |scratch: &Path, output: &Path| { (self.generate)(&Job { + language: self.name, companions, tool, name: self.tool, @@ -122,7 +123,7 @@ impl Renderer { output, }) }; - if format == Format::Txt { + 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"); @@ -146,6 +147,7 @@ impl Renderer { } struct Job<'a> { + language: &'static str, companions: &'a [(&'a str, std::path::PathBuf)], tool: &'a Path, name: &'static str, @@ -865,3 +867,28 @@ pub const PENROSE: Renderer = Renderer { 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, +}; diff --git a/extensions/diagram/src/renderer/plantuml.rs b/extensions/diagram/src/renderer/plantuml.rs new file mode 100644 index 000000000..2303a7281 --- /dev/null +++ b/extensions/diagram/src/renderer/plantuml.rs @@ -0,0 +1,88 @@ +use super::Job; +use crate::asset; +use crate::asset::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), + ) +} From 51714b320386ac233e4030c8314bdaab0f5cdd20 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 22:02:39 +0100 Subject: [PATCH 56/60] feat(diagram): render salt blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ .../src/subcommands/convert/extensions.rs | 1 + acdc-cli/tests/convert/diagram.rs | 12 ++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 ++++ extensions/diagram/src/renderer.rs | 23 +++++++++++++++++++ 6 files changed, 44 insertions(+) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 3a851d86d..ef2797ee6 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index f443e9226..1b55eb37c 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -191,6 +191,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (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()), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 252db4627..86a988fba 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -506,6 +506,18 @@ 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' '' "#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 119f1f8a2..6a0c1d70c 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index eb22fd6d8..b3e6ec641 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -241,6 +241,10 @@ Render `[penrose]` blocks and `penrose::chart.substance[]` files with `--roger P 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 1d2c817bc..e0f4b5725 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -892,3 +892,26 @@ pub const PLANTUML: Renderer = Renderer { ], 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, +}; From 930774b1581357d9da762fb9d5705171634750ae Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 22:03:53 +0100 Subject: [PATCH 57/60] feat(diagram): render vega blocks and file macros --- acdc-cli/CHANGELOG.md | 2 + .../src/subcommands/convert/extensions.rs | 49 ++++++++++++++----- acdc-cli/tests/convert/diagram.rs | 13 +++++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 4 ++ extensions/diagram/src/renderer.rs | 38 ++++++++++++++ 6 files changed, 95 insertions(+), 13 deletions(-) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index ef2797ee6..dcfd2bd81 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 1b55eb37c..3e568478c 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -156,6 +156,15 @@ pub(super) struct DiagramArgs { /// 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, /// Path to the trusted bytefield-svg executable #[arg(long, value_name = "PATH")] bytefield_svg: Option, @@ -191,6 +200,7 @@ impl DiagramArgs { &self, ) -> impl Iterator { [ + (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()), @@ -238,6 +248,31 @@ impl DiagramArgs { .filter_map(|(renderer, path): (_, Option<&Path>)| path.map(|p| (renderer, p))) } + fn register_configured( + &self, + registry: &mut RegistryBuilder, + output: OutputDirectories<'_>, + ) -> Result<()> { + let companions: Vec<_> = [ + ("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() @@ -389,19 +424,7 @@ impl DiagramArgs { .register_block_style(style) .map_err(|e| error::display(&e))?; } - let companions: Vec<_> = [("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))?; - } + self.register_configured(&mut registry, output)?; let mut catalog = available.clone(); catalog .register("diagram", registry.build()) diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 86a988fba..b6970077d 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -518,6 +518,19 @@ 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' '' "#, + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 6a0c1d70c..08193bb9b 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index b3e6ec641..c53100e25 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -245,6 +245,10 @@ Render `[plantuml]` blocks and `plantuml::chart.puml[]` files with `--plantuml P 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index e0f4b5725..1b6427bd0 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -915,3 +915,41 @@ pub const SALT: Renderer = Renderer { ], generate: plantuml::render, }; + +fn vega(job: &Job<'_>) -> io::Result<()> { + let is_lite = 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(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 { + 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, +}; From 8683e71583b57d52fe83ab5fc47f385d3b925c19 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 22:04:29 +0100 Subject: [PATCH 58/60] feat(diagram): render vegalite blocks and file macros --- acdc-cli/CHANGELOG.md | 2 ++ .../src/subcommands/convert/extensions.rs | 2 ++ acdc-cli/tests/convert/diagram.rs | 20 +++++++++++++ extensions/diagram/CHANGELOG.md | 2 ++ extensions/diagram/README.adoc | 4 +++ extensions/diagram/src/renderer.rs | 28 +++++++++++++++++-- 6 files changed, 55 insertions(+), 3 deletions(-) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index dcfd2bd81..2ae9dcb20 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 3e568478c..56b6df13e 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -200,6 +200,7 @@ impl DiagramArgs { &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()), @@ -254,6 +255,7 @@ impl DiagramArgs { 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()), diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index b6970077d..db68f5538 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -531,6 +531,26 @@ 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' '' "#, + )], + ) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 08193bb9b..b847e03d4 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index c53100e25..7828a5260 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -249,6 +249,10 @@ Render `[salt]` blocks and `salt::chart.salt[]` files with `--plantuml PATH`. Su 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`. + == 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. diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 1b6427bd0..57852aada 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -917,16 +917,29 @@ pub const SALT: Renderer = Renderer { }; fn vega(job: &Job<'_>) -> io::Result<()> { - let is_lite = job.source.contains("/schema/vega-lite/") || job.option("vegalite").is_some(); + 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(job.companion("vl2vg")?), Some(&path))?; + 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 { - job.tool + if job.language == "vegalite" { + job.companion("vg2svg")? + } else { + job.tool + } } else { job.companion("vg2png")? }; @@ -953,3 +966,12 @@ pub const VEGA: Renderer = Renderer { 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, +}; From dca2feaa97e95d5b09728d27b05171fb46b61077 Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 22:05:07 +0100 Subject: [PATCH 59/60] feat(diagram): caption local images with the meme macro --- acdc-cli/CHANGELOG.md | 2 + .../src/subcommands/convert/extensions.rs | 13 +- acdc-cli/tests/convert/diagram.rs | 52 +++- extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 4 + extensions/diagram/src/lib.rs | 2 + extensions/diagram/src/meme.rs | 290 ++++++++++++++++++ 7 files changed, 363 insertions(+), 2 deletions(-) create mode 100644 extensions/diagram/src/meme.rs diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 2ae9dcb20..3da4182b7 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- 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. diff --git a/acdc-cli/src/subcommands/convert/extensions.rs b/acdc-cli/src/subcommands/convert/extensions.rs index 56b6df13e..260b3e9d6 100644 --- a/acdc-cli/src/subcommands/convert/extensions.rs +++ b/acdc-cli/src/subcommands/convert/extensions.rs @@ -165,6 +165,9 @@ pub(super) struct DiagramArgs { /// 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, @@ -283,6 +286,7 @@ impl DiagramArgs { || 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() } @@ -296,7 +300,7 @@ impl DiagramArgs { use std::collections::{HashMap, hash_map::Entry}; if !self.has_renderer() { return Err(miette::miette!( - "--extension diagram requires --wavedrom-cli PATH, --lualatex PATH, --graphviz-dot PATH, --mscgen PATH, --dpic PATH, --pikchr PATH, --goat PATH, or --bytefield-svg PATH" + "--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. @@ -427,6 +431,13 @@ impl DiagramArgs { .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()) diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index db68f5538..7eda77dab 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -37,7 +37,10 @@ fn diagram_is_unavailable_before_input_is_read() -> TestResult { fn diagram_configuration_requires_activation_and_tools() -> TestResult { let dir = tempfile::tempdir()?; for (args, expected) in [ - (vec!["--extension", "diagram"], "requires --wavedrom-cli"), + ( + vec!["--extension", "diagram"], + "requires at least one renderer executable", + ), ( vec!["--bytefield-svg", "missing"], "require --extension diagram", @@ -551,6 +554,53 @@ 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(()) + } + fn tool_sample( style: &str, flag: &str, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index b847e03d4..47f6a2045 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [Unreleased] +- 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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index 7828a5260..dd07ec458 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -253,6 +253,10 @@ Render `[vega]` blocks and `vega::chart.json[]` files with `--vg2svg PATH`. SVG 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. + == 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. diff --git a/extensions/diagram/src/lib.rs b/extensions/diagram/src/lib.rs index 7261189e2..cd7054c20 100644 --- a/extensions/diagram/src/lib.rs +++ b/extensions/diagram/src/lib.rs @@ -20,6 +20,7 @@ mod dpic; mod file_macro; mod goat; mod graphviz; +mod meme; mod msc; mod pikchr; pub mod renderer; @@ -32,6 +33,7 @@ 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; 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) + } +} From 3f5a532465f0809a6de5b04d2c46192a6127320e Mon Sep 17 00:00:00 2001 From: Norberto Lopes Date: Sat, 21 Nov 2026 22:06:46 +0100 Subject: [PATCH 60/60] fix(diagram): honor renderer options and file image dimensions --- acdc-cli/CHANGELOG.md | 2 + acdc-cli/tests/convert/diagram.rs | 55 +++++++++++++++++++++ extensions/diagram/CHANGELOG.md | 2 + extensions/diagram/README.adoc | 8 ++- extensions/diagram/src/asset.rs | 7 +++ extensions/diagram/src/file_macro.rs | 3 +- extensions/diagram/src/renderer.rs | 30 ++++++++++- extensions/diagram/src/renderer/oxdraw.rs | 3 +- extensions/diagram/src/renderer/plantuml.rs | 3 +- 9 files changed, 105 insertions(+), 8 deletions(-) diff --git a/acdc-cli/CHANGELOG.md b/acdc-cli/CHANGELOG.md index 3da4182b7..2c3322b25 100644 --- a/acdc-cli/CHANGELOG.md +++ b/acdc-cli/CHANGELOG.md @@ -7,6 +7,8 @@ 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. diff --git a/acdc-cli/tests/convert/diagram.rs b/acdc-cli/tests/convert/diagram.rs index 7eda77dab..b84e4771d 100644 --- a/acdc-cli/tests/convert/diagram.rs +++ b/acdc-cli/tests/convert/diagram.rs @@ -601,6 +601,61 @@ esac 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, diff --git a/extensions/diagram/CHANGELOG.md b/extensions/diagram/CHANGELOG.md index 47f6a2045..c219445af 100644 --- a/extensions/diagram/CHANGELOG.md +++ b/extensions/diagram/CHANGELOG.md @@ -2,6 +2,8 @@ ## [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. diff --git a/extensions/diagram/README.adoc b/extensions/diagram/README.adoc index dd07ec458..ed655807d 100644 --- a/extensions/diagram/README.adoc +++ b/extensions/diagram/README.adoc @@ -203,7 +203,7 @@ Render `[ditaa]` blocks and `ditaa::chart.ditaa[]` files with `--ditaa PATH`. Ch == tape -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. Enable the package with `--extension diagram`. +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 @@ -257,6 +257,12 @@ Render `[vegalite]` blocks and `vegalite::chart.json[]` files with `--vl2vg PATH 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. diff --git a/extensions/diagram/src/asset.rs b/extensions/diagram/src/asset.rs index c5c77bc32..3c3ab37f8 100644 --- a/extensions/diagram/src/asset.rs +++ b/extensions/diagram/src/asset.rs @@ -69,6 +69,13 @@ impl Format { } } + 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 { diff --git a/extensions/diagram/src/file_macro.rs b/extensions/diagram/src/file_macro.rs index 5b9148b96..98d6f2f9e 100644 --- a/extensions/diagram/src/file_macro.rs +++ b/extensions/diagram/src/file_macro.rs @@ -56,7 +56,8 @@ where !matches!( name, "target" | "format" | "on-error" | "scale" | "subs" | "svg-type" - ) && !renderer_arguments.contains(&name) + ) && (matches!(name, "width" | "height") + || !renderer_arguments.contains(&name)) }); if attributes.is_empty() { image diff --git a/extensions/diagram/src/renderer.rs b/extensions/diagram/src/renderer.rs index 57852aada..cc7ba3955 100644 --- a/extensions/diagram/src/renderer.rs +++ b/extensions/diagram/src/renderer.rs @@ -61,6 +61,32 @@ impl Renderer { 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, @@ -86,7 +112,7 @@ impl Renderer { Some(name) => *self .formats .iter() - .find(|format| format.extension() == name) + .find(|format| format.matches_name(name)) .ok_or_else(|| { format!( "unsupported {} format '{name}' (expected {})", @@ -102,7 +128,7 @@ impl Renderer { let options: Vec<_> = self .attributes .iter() - .filter_map(|&key| diagram_attribute(input, self.name, key).map(|value| (key, value))) + .filter_map(|&key| self.option(input, key).map(|value| (key, value))) .collect(); let source = diagram_source(input); let identity = options diff --git a/extensions/diagram/src/renderer/oxdraw.rs b/extensions/diagram/src/renderer/oxdraw.rs index 78c10b26e..650481d64 100644 --- a/extensions/diagram/src/renderer/oxdraw.rs +++ b/extensions/diagram/src/renderer/oxdraw.rs @@ -1,6 +1,5 @@ use super::Job; -use crate::asset; -use crate::asset::Format; +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); diff --git a/extensions/diagram/src/renderer/plantuml.rs b/extensions/diagram/src/renderer/plantuml.rs index 2303a7281..87ddf714c 100644 --- a/extensions/diagram/src/renderer/plantuml.rs +++ b/extensions/diagram/src/renderer/plantuml.rs @@ -1,6 +1,5 @@ use super::Job; -use crate::asset; -use crate::asset::Format; +use crate::asset::{self, Format}; use std::{io, process::Command}; pub(super) fn render(job: &Job<'_>) -> io::Result<()> { let tag = if job.language == "salt" {