diff --git a/CHANGELOG.md b/CHANGELOG.md index 84bb186..2e552f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## Unreleased + +- SVG `` support: text labels in SVGs generated by mermaid-cli, draw.io, and D3.js now render correctly. Embedded HTML is converted to native SVG `` elements before rendering. Structural HTML (tables, lists, nested divs) is preserved as readable text with row/cell separation. +- SVG text inherits fill color and font-family from the document's stylesheet. +- SVG `` elements inside `` with an existing `` fallback are left untouched. +- SVG `` x/y positioning attributes are respected. +- Expanded HTML entity decoding: numeric character references (`&#NNN;`, `&#xHHH;`) and common named entities (` `, `—`, `→`, etc.) are now decoded in foreignObject text. + ## 0.1.2 - Animated GIF playback via `--animate` flag (kitty animation protocol) diff --git a/Cargo.lock b/Cargo.lock index 80c605b..9c48906 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -352,6 +352,7 @@ dependencies = [ "clap_complete", "image", "resvg", + "roxmltree 0.21.1", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 23e3974..977c9e3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,7 +2,7 @@ name = "kittyview" version = "0.1.2" edition = "2024" -rust-version = "1.85" +rust-version = "1.87" license = "Apache-2.0" description = "Display images in kitty-compatible terminals" repository = "https://github.com/gominimal/kittyview" @@ -30,3 +30,4 @@ resvg = "0.47" clap = { version = "4", features = ["derive"] } clap_complete = "4" base64 = "0.22" +roxmltree = "0.21" diff --git a/README.md b/README.md index e96a14c..9a295df 100644 --- a/README.md +++ b/README.md @@ -100,7 +100,7 @@ kittyview completions fish > ~/.config/fish/completions/kittyview.fish | PNG | `.png` | | JPEG | `.jpg`, `.jpeg` | | GIF | `.gif` | -| SVG | `.svg`, `.svgz` (with full text rendering) | +| SVG | `.svg`, `.svgz` (text rendering, see [SVG notes](#svg-text-rendering)) | | WebP | `.webp` | | BMP | `.bmp` | | TIFF | `.tif`, `.tiff` | @@ -113,6 +113,19 @@ kittyview completions fish > ~/.config/fish/completions/kittyview.fish SVG files are detected by extension or by content sniffing (`` elements out of the box. + +Many tools (mermaid-cli, draw.io, D3.js) generate SVGs that use `` with embedded HTML for text labels instead of native `` elements. kittyview detects these and converts them to `` on a best-effort basis. This covers the common cases well, but has some limitations: + +- **Text wrapping**: HTML text that relies on CSS word-wrap (without explicit `
` tags) will render as a single line. Most mermaid diagrams use `
` and are unaffected. +- **Rich formatting**: Bold, italic, and per-element font size or color differences inside labels are not preserved. The global font and color from the SVG's stylesheet are used. +- **Structural HTML**: Tables, lists, and nested divs are rendered as readable plain text (cells separated by tabs, rows and list items on separate lines) but without visual table/list formatting. MathML and form elements are not supported. +- **Edge label backgrounds**: Semi-transparent background rectangles behind edge labels are not reproduced. + +SVGs that already use native `` elements (e.g. Inkscape, some mermaid-cli configurations) render without these limitations. + ## SVG resource access When rendering SVGs, external file references (``) are blocked by default. Use `--svg-resources` to control this: @@ -147,7 +160,7 @@ cat diagram.svg | kittyview --svg-resources tree ## Building from source -Requires Rust 1.85+ (edition 2024). +Requires Rust 1.87+ (edition 2024). ``` cargo build --release diff --git a/SECURITY.md b/SECURITY.md index b3ee83b..490561c 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -11,6 +11,7 @@ Do **not** open a public issue for security vulnerabilities. Security-relevant areas of kittyview include: - **SVG rendering**: SVGs are a rich format that can reference external files, embed scripts, and contain deeply nested structures. kittyview uses [resvg](https://github.com/linebender/resvg) (pure Rust, no scripting support) and defaults to blocking external file access (`--svg-resources none`). +- **SVG foreignObject conversion**: SVGs containing `` elements (common in mermaid-cli, draw.io, and D3.js output) are preprocessed before rendering. Embedded HTML is stripped to plain text and replaced with native SVG `` elements. No HTML is interpreted or executed -- all markup is discarded and only text content is preserved. Entity decoding is limited to a fixed set of named entities and numeric character references. - **Image decoding**: Malformed images could trigger bugs in decoder libraries. All decoders are pure Rust (no C code). - **Terminal escape sequences**: Malformed output could corrupt terminal state. kittyview buffers all protocol output before writing and validates terminal support before emitting. diff --git a/src/svg.rs b/src/svg.rs index 666aed3..01b390f 100644 --- a/src/svg.rs +++ b/src/svg.rs @@ -3,6 +3,11 @@ use resvg::usvg; use std::path::Path; +/// Default font size used by mermaid-generated SVGs. +const MERMAID_FONT_SIZE: f64 = 16.0; +/// Line height multiplier for multi-line text (matches mermaid's line-height: 1.5). +const LINE_HEIGHT: f64 = 1.5; + /// Maximum dimension (width or height) for the rendered pixmap. /// 8192x8192 * 4 bytes = 256MB, which is a reasonable upper bound. const MAX_DIMENSION: u32 = 8192; @@ -69,6 +74,429 @@ fn make_string_resolver(policy: SvgResources) -> usvg::ImageHrefStringResolverFn }) } +/// Extract plain-text lines from a foreignObject's HTML content. +/// +/// Mermaid wraps label text in `

text
more

`. +/// We strip all HTML tags (injecting newlines at block boundaries and `
`) +/// and split the result into lines. +fn extract_text_lines(html: &str) -> Vec { + let text = strip_tags(html); + text.split('\n') + .map(|line| line.trim().to_string()) + .filter(|line| !line.is_empty()) + .collect() +} + +/// Remove XML/HTML tags from a string, returning only text content. +/// Inserts whitespace at structural HTML boundaries (table cells, list items, +/// paragraphs) so that stripped text remains readable. +fn strip_tags(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut inside_tag = false; + let mut tag_buf = String::new(); + for ch in s.chars() { + match ch { + '<' => { + inside_tag = true; + tag_buf.clear(); + } + '>' => { + inside_tag = false; + // Inject separators based on the closing tag name. + let tag = tag_buf.trim().to_ascii_lowercase(); + let tag_name = tag + .strip_prefix('/') + .unwrap_or(&tag) + .split_whitespace() + .next() + .unwrap_or(""); + let is_closing = tag.starts_with('/'); + match tag_name { + //
/
— always a newline (void element, never has a closing tag) + "br" => out.push('\n'), + _ if is_closing => match tag_name { + // Block-level / row boundaries → newline + "tr" | "p" | "div" | "li" | "dt" | "dd" | "h1" | "h2" | "h3" | "h4" + | "h5" | "h6" | "blockquote" | "pre" => out.push('\n'), + // Cell boundaries → tab + "td" | "th" => out.push('\t'), + _ => {} + }, + _ => {} + } + } + _ if !inside_tag => out.push(ch), + _ => tag_buf.push(ch), + } + } + decode_entities(&out) +} + +/// Decode HTML/XML character entities and numeric character references. +fn decode_entities(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars().peekable(); + while let Some(ch) = chars.next() { + if ch != '&' { + out.push(ch); + continue; + } + // Collect entity name up to ';' (or give up after 10 chars) + let mut entity = String::new(); + let mut terminated = false; + for _ in 0..10 { + match chars.peek() { + Some(&';') => { + chars.next(); + terminated = true; + break; + } + Some(&c) => { + entity.push(c); + chars.next(); + } + None => break, + } + } + if !terminated { + // Not a valid entity reference; emit literally + out.push('&'); + out.push_str(&entity); + continue; + } + match decode_named_or_numeric(&entity) { + Some(decoded) => out.push(decoded), + None => { + // Unknown entity; emit literally + out.push('&'); + out.push_str(&entity); + out.push(';'); + } + } + } + out +} + +/// Decode a single named or numeric entity (without the & and ;). +fn decode_named_or_numeric(entity: &str) -> Option { + // Numeric references: &#NNN; or &#xHHH; + if let Some(rest) = entity.strip_prefix('#') { + let code = if let Some(hex) = rest.strip_prefix('x').or_else(|| rest.strip_prefix('X')) { + u32::from_str_radix(hex, 16).ok()? + } else { + rest.parse::().ok()? + }; + return char::from_u32(code); + } + // Named entities (common subset) + match entity { + "amp" => Some('&'), + "lt" => Some('<'), + "gt" => Some('>'), + "quot" => Some('"'), + "apos" => Some('\''), + "nbsp" => Some('\u{00A0}'), + "ndash" => Some('\u{2013}'), + "mdash" => Some('\u{2014}'), + "lsquo" => Some('\u{2018}'), + "rsquo" => Some('\u{2019}'), + "ldquo" => Some('\u{201C}'), + "rdquo" => Some('\u{201D}'), + "hellip" => Some('\u{2026}'), + "bull" => Some('\u{2022}'), + "copy" => Some('\u{00A9}'), + "reg" => Some('\u{00AE}'), + "trade" => Some('\u{2122}'), + "times" => Some('\u{00D7}'), + "divide" => Some('\u{00F7}'), + "larr" => Some('\u{2190}'), + "rarr" => Some('\u{2192}'), + "uarr" => Some('\u{2191}'), + "darr" => Some('\u{2193}'), + _ => None, + } +} + +/// Information about a single foreignObject to be replaced. +struct ForeignObjectInfo { + /// Byte range of the entire `...` in the source. + start: usize, + end: usize, + /// Position and size of the foreignObject region. + x: f64, + y: f64, + width: f64, + height: f64, + /// Extracted text lines. + lines: Vec, + /// Font size parsed from the SVG or default. + font_size: f64, + /// Text fill color (e.g. "#333"). + fill: String, + /// Font family string (e.g. "trebuchet ms", verdana, arial, sans-serif). + font_family: String, +} + +/// Detect `` elements in the SVG and replace them with `` elements +/// that resvg can render. Returns the (possibly modified) SVG bytes. +/// +/// This is a best-effort conversion targeting mermaid-cli output. If parsing fails or +/// no foreignObject elements are found, the original bytes are returned unchanged. +pub fn convert_foreign_objects(svg_data: &[u8]) -> Vec { + let svg_str = match std::str::from_utf8(svg_data) { + Ok(s) => s, + Err(_) => return svg_data.to_vec(), + }; + + let doc = match roxmltree::Document::parse(svg_str) { + Ok(d) => d, + Err(_) => return svg_data.to_vec(), + }; + + // Detect global defaults from the SVG's embedded styles. + let font_size = detect_font_size(&doc).unwrap_or(MERMAID_FONT_SIZE); + let fill = detect_fill(&doc).unwrap_or_else(|| "#000".to_string()); + let font_family = detect_font_family(&doc).unwrap_or_default(); + + // Collect all foreignObject elements. + let mut replacements: Vec = Vec::new(); + + for node in doc.descendants() { + if node.tag_name().name() != "foreignObject" { + continue; + } + + // Skip foreignObjects inside a that already has a fallback sibling. + // Well-formed SVGs use with foreignObject + fallback . + if let Some(parent) = node.parent() { + if parent.tag_name().name() == "switch" + && parent.children().any(|c| c.tag_name().name() == "text") + { + continue; + } + } + + let x: f64 = node + .attribute("x") + .and_then(|v| v.parse().ok()) + .unwrap_or(0.0); + let y: f64 = node + .attribute("y") + .and_then(|v| v.parse().ok()) + .unwrap_or(0.0); + let width: f64 = node + .attribute("width") + .and_then(|v| v.parse().ok()) + .unwrap_or(0.0); + let height: f64 = node + .attribute("height") + .and_then(|v| v.parse().ok()) + .unwrap_or(0.0); + + // Skip empty/zero-sized placeholders + if width == 0.0 || height == 0.0 { + continue; + } + + // Get the raw HTML content inside the foreignObject + let range = node.range(); + let inner_html = &svg_str[range.start..range.end]; + + let lines = extract_text_lines(inner_html); + if lines.is_empty() { + continue; + } + + replacements.push(ForeignObjectInfo { + start: range.start, + end: range.end, + x, + y, + width, + height, + lines, + font_size, + fill: fill.clone(), + font_family: font_family.clone(), + }); + } + + if replacements.is_empty() { + return svg_data.to_vec(); + } + + // Apply replacements in reverse order so byte offsets remain valid. + let mut result = svg_str.to_string(); + replacements.sort_by(|a, b| b.start.cmp(&a.start)); + + for info in &replacements { + let text_elem = build_text_element(info); + result.replace_range(info.start..info.end, &text_elem); + } + + result.into_bytes() +} + +/// Build an SVG `` element that approximates the foreignObject's rendered text. +fn build_text_element(info: &ForeignObjectInfo) -> String { + let cx = info.x + info.width / 2.0; + let num_lines = info.lines.len(); + let line_step = info.font_size * LINE_HEIGHT; + + // Common attributes shared by single-line and multi-line variants. + let font_attr = if info.font_family.is_empty() { + String::new() + } else { + format!(" font-family=\"{}\"", xml_escape(&info.font_family)) + }; + + if num_lines == 1 { + let cy = info.y + info.height / 2.0; + format!( + "{text}", + fs = info.font_size, + fill = xml_escape(&info.fill), + font = font_attr, + text = xml_escape(&info.lines[0]), + ) + } else { + // Multi-line: center the block vertically. + let block_height = (num_lines as f64 - 1.0) * line_step; + let first_y = info.y + info.height / 2.0 - block_height / 2.0; + + let mut s = format!( + "", + fs = info.font_size, + fill = xml_escape(&info.fill), + font = font_attr, + ); + for (i, line) in info.lines.iter().enumerate() { + let y = first_y + i as f64 * line_step; + s.push_str(&format!( + "{text}", + text = xml_escape(line), + )); + } + s.push_str(""); + s + } +} + +/// XML escaping for text content and attribute values. +fn xml_escape(s: &str) -> String { + s.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) +} + +/// Try to extract the default font-size from the SVG's embedded styles. +fn detect_font_size(doc: &roxmltree::Document) -> Option { + // Look for font-size in the root style attribute or a