From 91e85df195d0808b5ffa12c8aae7a2a5740d85f2 Mon Sep 17 00:00:00 2001 From: msample <4896732+msample@users.noreply.github.com> Date: Fri, 3 Apr 2026 22:07:44 -0700 Subject: [PATCH 1/2] add multiplexer (tmux, screen) support. Fix svg text rendering issue wrt font availability. See CHANGELOG --- CHANGELOG.md | 10 + Cargo.lock | 3 +- Cargo.toml | 1 + src/kitty.rs | 187 +++++-- src/logo.rs | 20 +- src/main.rs | 129 ++++- src/svg.rs | 91 +++- src/terminal.rs | 1154 +++++++++++++++++++++++++++++++++++++++++++ test/visual-test.sh | 182 +++++++ 9 files changed, 1694 insertions(+), 83 deletions(-) create mode 100644 src/terminal.rs create mode 100755 test/visual-test.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index 8203385..12231f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## Unreleased + +- **Terminal multiplexer passthrough**: kittyview now auto-detects tmux and GNU screen via in-band terminal queries (XTVERSION, DA2) and automatically wraps kitty graphics sequences in DCS passthrough envelopes. Requires `set -g allow-passthrough on` in tmux.conf. +- **Nested multiplexer support**: detects and wraps through multiple multiplexer layers (e.g. tmux-in-tmux, tmux-in-screen). Each layer is probed recursively up to 4 levels deep. +- **`--passthrough` flag**: manually specify the multiplexer stack (`auto`, `off`, or comma-separated layers like `tmux`, `tmux,tmux`, `tmux,screen`). +- **In-band terminal detection**: terminal identity is now detected via XTVERSION/DA2 escape sequence queries through stdin (or `/dev/tty` when stdin is piped), replacing the previous env-var-only approach. Env vars serve as fallback when no terminal I/O is available. +- **Font fallback for SVG text**: sans-serif, serif, and monospace font family mappings now try a list of common fonts (Liberation, DejaVu, Helvetica, Arial, etc.) instead of hardcoding Liberation fonts. Fixes blank text on systems without Liberation fonts installed (e.g. macOS). +- Fixed `
` (self-closing, no space) not producing line breaks in foreignObject text extraction. +- Added `test/visual-test.sh` for human-in-the-loop visual regression testing of SVG text rendering. + ## 0.1.3 - 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. diff --git a/Cargo.lock b/Cargo.lock index 9c48906..252f925 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -345,12 +345,13 @@ checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" [[package]] name = "kittyview" -version = "0.1.2" +version = "0.1.3" dependencies = [ "base64", "clap", "clap_complete", "image", + "libc", "resvg", "roxmltree 0.21.1", ] diff --git a/Cargo.toml b/Cargo.toml index 7684e6f..1c1f1cb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,3 +31,4 @@ clap = { version = "4", features = ["derive"] } clap_complete = "4" base64 = "0.22" roxmltree = "0.21" +libc = "0.2" diff --git a/src/kitty.rs b/src/kitty.rs index 08c9d32..c1750e9 100644 --- a/src/kitty.rs +++ b/src/kitty.rs @@ -1,50 +1,37 @@ // SPDX-License-Identifier: Apache-2.0 +use crate::terminal::{Mux, wrap_for_stack}; use base64::{Engine as _, engine::general_purpose::STANDARD}; use std::io::{self, Write}; /// Maximum bytes of base64 data per chunk (kitty protocol limit). const CHUNK_SIZE: usize = 4096; -/// Check whether the terminal likely supports the kitty graphics protocol, -/// based on environment variables set by known-compatible terminals. -pub fn is_supported() -> bool { - if std::env::var_os("KITTY_WINDOW_ID").is_some() { - return true; - } - if std::env::var_os("KONSOLE_VERSION").is_some() { - return true; - } - if let Some(prog) = std::env::var_os("TERM_PROGRAM") { - let prog = prog.to_string_lossy(); - if matches!( - prog.as_ref(), - "kitty" | "WezTerm" | "ghostty" | "Ghostty" | "iTerm.app" | "iTerm2" - ) { - return true; - } - } - if let Some(term) = std::env::var_os("TERM") { - let term = term.to_string_lossy(); - let term = term.to_ascii_lowercase(); - if ["kitty", "ghostty", "wezterm"] - .iter() - .any(|t| term.contains(t)) - { - return true; - } +/// Write a single APC sequence to the output buffer, wrapped for the mux stack. +fn write_apc(buf: &mut Vec, apc: &[u8], mux_stack: &[Mux]) { + if mux_stack.is_empty() || mux_stack.iter().all(|m| matches!(m, Mux::Zellij)) { + buf.extend_from_slice(apc); + } else { + buf.extend_from_slice(&wrap_for_stack(apc, mux_stack)); } - false } /// Write a single image's base64-encoded data with the given header parameters. -/// Handles chunking transparently. -fn write_frame_data(buf: &mut Vec, png_data: &[u8], header: &str) -> io::Result<()> { +/// Handles chunking transparently. Each APC chunk is individually wrapped for +/// the multiplexer stack. +fn write_frame_data( + buf: &mut Vec, + png_data: &[u8], + header: &str, + mux_stack: &[Mux], +) -> io::Result<()> { let encoded = STANDARD.encode(png_data); let bytes = encoded.as_bytes(); if bytes.len() <= CHUNK_SIZE { - write!(buf, "\x1b_G{header};{encoded}\x1b\\")?; + let mut apc = Vec::new(); + write!(apc, "\x1b_G{header};{encoded}\x1b\\")?; + write_apc(buf, &apc, mux_stack); } else { let mut offset = 0; let mut first = true; @@ -54,12 +41,14 @@ fn write_frame_data(buf: &mut Vec, png_data: &[u8], header: &str) -> io::Res let chunk = &encoded[offset..end]; let is_last = end == bytes.len(); + let mut apc = Vec::new(); if first { - write!(buf, "\x1b_G{header},m={};{chunk}\x1b\\", u8::from(!is_last))?; + write!(apc, "\x1b_G{header},m={};{chunk}\x1b\\", u8::from(!is_last))?; first = false; } else { - write!(buf, "\x1b_Gm={};{chunk}\x1b\\", u8::from(!is_last))?; + write!(apc, "\x1b_Gm={};{chunk}\x1b\\", u8::from(!is_last))?; } + write_apc(buf, &apc, mux_stack); offset = end; } } @@ -67,28 +56,36 @@ fn write_frame_data(buf: &mut Vec, png_data: &[u8], header: &str) -> io::Res } /// Display a single PNG image via the kitty graphics protocol. -pub fn display_png(png_data: &[u8], out: &mut impl Write) -> io::Result<()> { +pub fn display_png( + png_data: &[u8], + out: &mut impl Write, + mux_stack: &[Mux], +) -> io::Result<()> { let mut buf = Vec::with_capacity(png_data.len() * 2); - write_frame_data(&mut buf, png_data, "a=T,f=100")?; + write_frame_data(&mut buf, png_data, "a=T,f=100", mux_stack)?; out.write_all(&buf)?; out.flush() } /// Display an animated image via the kitty graphics protocol. /// Each frame is a `(png_bytes, delay_ms)` pair. -pub fn display_animation(frames: &[(Vec, u32)], out: &mut impl Write) -> io::Result<()> { +pub fn display_animation( + frames: &[(Vec, u32)], + out: &mut impl Write, + mux_stack: &[Mux], +) -> io::Result<()> { if frames.is_empty() { return Ok(()); } if frames.len() == 1 { - return display_png(&frames[0].0, out); + return display_png(&frames[0].0, out, mux_stack); } let mut buf = Vec::new(); const ID: u32 = 1; // Base frame (frame 1) - write_frame_data(&mut buf, &frames[0].0, &format!("a=T,f=100,i={ID},q=2"))?; + write_frame_data(&mut buf, &frames[0].0, &format!("a=T,f=100,i={ID},q=2"), mux_stack)?; // Additional frames for (i, (png_data, delay_ms)) in frames.iter().enumerate().skip(1) { @@ -97,15 +94,18 @@ pub fn display_animation(frames: &[(Vec, u32)], out: &mut impl Write) -> io: &mut buf, png_data, &format!("a=f,i={ID},r={r},z={delay_ms},f=100,q=2"), + mux_stack, )?; } // Set frame 1's gap and start looping (s=3 = loop, v=1 = start) let first_delay = frames[0].1; + let mut apc = Vec::new(); write!( - buf, + apc, "\x1b_Ga=a,i={ID},r=1,z={first_delay},s=3,v=1,q=2;\x1b\\" )?; + write_apc(&mut buf, &apc, mux_stack); out.write_all(&buf)?; out.flush() @@ -119,7 +119,7 @@ mod tests { fn single_chunk_format() { let data = b"tiny"; let mut out = Vec::new(); - display_png(data, &mut out).unwrap(); + display_png(data, &mut out, &[]).unwrap(); let output = String::from_utf8(out).unwrap(); assert!(output.starts_with("\x1b_Ga=T,f=100;")); assert!(output.ends_with("\x1b\\")); @@ -130,7 +130,7 @@ mod tests { fn multi_chunk_format() { let data = vec![0xABu8; 4000]; let mut out = Vec::new(); - display_png(&data, &mut out).unwrap(); + display_png(&data, &mut out, &[]).unwrap(); let output = String::from_utf8(out).unwrap(); assert!(output.starts_with("\x1b_Ga=T,f=100,m=1;")); assert!(output.contains("m=0;")); @@ -141,7 +141,7 @@ mod tests { fn all_chunks_terminated() { let data = vec![0u8; 8000]; let mut out = Vec::new(); - display_png(&data, &mut out).unwrap(); + display_png(&data, &mut out, &[]).unwrap(); let output = String::from_utf8(out).unwrap(); let starts = output.matches("\x1b_G").count(); let ends = output.matches("\x1b\\").count(); @@ -152,7 +152,7 @@ mod tests { fn payload_is_valid_base64() { let data = b"hello kitty"; let mut out = Vec::new(); - display_png(data, &mut out).unwrap(); + display_png(data, &mut out, &[]).unwrap(); let output = String::from_utf8(out).unwrap(); let payload_start = output.find(';').unwrap() + 1; let payload_end = output.rfind("\x1b\\").unwrap(); @@ -166,7 +166,7 @@ mod tests { #[test] fn empty_input() { let mut out = Vec::new(); - display_png(b"", &mut out).unwrap(); + display_png(b"", &mut out, &[]).unwrap(); let output = String::from_utf8(out).unwrap(); assert!(output.starts_with("\x1b_Ga=T,f=100;")); assert!(output.ends_with("\x1b\\")); @@ -176,9 +176,8 @@ mod tests { fn animation_single_frame_delegates_to_display_png() { let frame = vec![(b"single".to_vec(), 100u32)]; let mut out = Vec::new(); - display_animation(&frame, &mut out).unwrap(); + display_animation(&frame, &mut out, &[]).unwrap(); let output = String::from_utf8(out).unwrap(); - // Should be a plain single image, no animation commands assert!(output.starts_with("\x1b_Ga=T,f=100;")); assert!(!output.contains("a=f")); assert!(!output.contains("a=a")); @@ -192,15 +191,103 @@ mod tests { (b"frame3".to_vec(), 200), ]; let mut out = Vec::new(); - display_animation(&frames, &mut out).unwrap(); + display_animation(&frames, &mut out, &[]).unwrap(); let output = String::from_utf8(out).unwrap(); - // Base frame with image ID assert!(output.contains("a=T,f=100,i=1")); - // Additional frames assert!(output.contains("a=f,i=1,r=2,z=150")); assert!(output.contains("a=f,i=1,r=3,z=200")); - // Animation start command with frame 1 gap and loop assert!(output.contains("a=a,i=1,r=1,z=100,s=3,v=1")); } + + // ── tmux wrapping tests ───────────────────────────────── + + #[test] + fn tmux_single_chunk_wrapped() { + let data = b"tiny"; + let mut out = Vec::new(); + let stack = [Mux::Tmux(None)]; + display_png(data, &mut out, &stack).unwrap(); + assert!(out.starts_with(b"\x1bPtmux;")); + assert!(out.ends_with(b"\x1b\\")); + assert!(out.windows(3).any(|w| w == b"\x1b\x1b_")); + } + + #[test] + fn tmux_multi_chunk_each_wrapped() { + let data = vec![0xABu8; 4000]; + let mut out = Vec::new(); + let stack = [Mux::Tmux(None)]; + display_png(&data, &mut out, &stack).unwrap(); + let tmux_starts = out.windows(7).filter(|w| *w == b"\x1bPtmux;").count(); + assert!(tmux_starts >= 2, "each chunk must be independently wrapped"); + } + + #[test] + fn tmux_animation_start_wrapped() { + let frames = vec![ + (b"f1".to_vec(), 100u32), + (b"f2".to_vec(), 150), + ]; + let mut out = Vec::new(); + let stack = [Mux::Tmux(None)]; + display_animation(&frames, &mut out, &stack).unwrap(); + let tmux_starts = out.windows(7).filter(|w| *w == b"\x1bPtmux;").count(); + assert!(tmux_starts >= 3, "animation start APC must also be wrapped"); + } + + #[test] + fn screen_single_chunk_wrapped() { + let data = b"tiny"; + let mut out = Vec::new(); + let stack = [Mux::Screen(None)]; + display_png(data, &mut out, &stack).unwrap(); + assert!(out.starts_with(b"\x1bP")); + assert!(!out.starts_with(b"\x1bPtmux;")); + assert!(out.windows(2).any(|w| w == b"\x1b_")); + } + + #[test] + fn no_mux_passthrough() { + let data = b"tiny"; + let mut out = Vec::new(); + display_png(data, &mut out, &[]).unwrap(); + assert!(!out.starts_with(b"\x1bP")); + assert!(out.starts_with(b"\x1b_G")); + } + + #[test] + fn zellij_no_wrapping() { + let data = b"tiny"; + let mut out = Vec::new(); + let stack = [Mux::Zellij]; + display_png(data, &mut out, &stack).unwrap(); + assert!(!out.starts_with(b"\x1bP")); + assert!(out.starts_with(b"\x1b_G")); + } + + #[test] + fn double_tmux_wrapping() { + let data = b"tiny"; + let mut out = Vec::new(); + let stack = [Mux::Tmux(None), Mux::Tmux(None)]; + display_png(data, &mut out, &stack).unwrap(); + // Outer tmux wrapper + assert!(out.starts_with(b"\x1bPtmux;")); + // Should contain a nested tmux wrapper (ESC P tmux; with doubled ESC) + assert!(out.windows(8).any(|w| w == b"\x1b\x1bPtmux;")); + } + + #[test] + fn tmux_in_screen_wrapping() { + let data = b"tiny"; + let mut out = Vec::new(); + let stack = [Mux::Tmux(None), Mux::Screen(None)]; + display_png(data, &mut out, &stack).unwrap(); + // Outer screen wrapper + assert!(out.starts_with(b"\x1bP")); + assert!(!out.starts_with(b"\x1bPtmux;")); + // Inner tmux wrapper should be present inside the screen DCS + assert!(out.windows(7).any(|w| w == b"\x1bPtmux;")); + } } diff --git a/src/logo.rs b/src/logo.rs index b0cc84f..3b1e49e 100644 --- a/src/logo.rs +++ b/src/logo.rs @@ -102,10 +102,7 @@ pub fn generate_animated_logo() -> Vec<(Vec, u32)> { // Load fonts once for all frames let mut opt = resvg::usvg::Options::default(); - opt.fontdb_mut().load_system_fonts(); - opt.fontdb_mut().set_sans_serif_family("Liberation Sans"); - opt.fontdb_mut().set_serif_family("Liberation Serif"); - opt.fontdb_mut().set_monospace_family("Liberation Mono"); + crate::svg::configure_fonts(&mut opt); // (kitten_b64, y_offset, delay_ms) let frame_specs: [(&str, u32, u32); 4] = [ @@ -231,4 +228,19 @@ mod tests { assert_eq!(img.width(), 480); assert_eq!(img.height(), 150); } + + #[test] + fn animated_logo_has_text_pixels() { + let frames = generate_animated_logo(); + let img = image::load_from_memory(&frames[0].0).unwrap().to_rgba8(); + // The speech bubble text ("kittyview") is dark purple (#2D1B69). + // Check for dark pixels in the right half of the image (where the bubble is). + let dark_in_bubble = img.enumerate_pixels().filter(|(x, _, p)| { + *x > 150 && p.0[0] < 80 && p.0[1] < 80 && p.0[2] < 120 && p.0[3] > 200 + }).count(); + assert!( + dark_in_bubble > 50, + "speech bubble should contain visible text pixels (got {dark_in_bubble})" + ); + } } diff --git a/src/main.rs b/src/main.rs index dab21b1..3d8172f 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,12 +3,46 @@ mod kitty; mod logo; mod svg; +mod terminal; use clap::{CommandFactory, Parser, Subcommand, ValueHint}; use std::fs; use std::io::{self, Cursor, IsTerminal, Read, Write}; use std::path::PathBuf; use std::process::ExitCode; +use terminal::Mux; + +/// Parse the `--passthrough` flag value into a mux stack. +/// +/// Accepts: `auto`, `off`, or a comma-separated list of `tmux`/`screen` +/// (innermost first). Examples: `tmux`, `tmux,tmux`, `tmux,screen`. +fn parse_passthrough(s: &str) -> Result>, String> { + let s = s.trim(); + match s { + "auto" => Ok(None), + "off" => Ok(Some(vec![])), + _ => { + let mut stack = Vec::new(); + for part in s.split(',') { + let part = part.trim(); + match part { + "tmux" => stack.push(Mux::Tmux(None)), + "screen" => stack.push(Mux::Screen(None)), + _ => { + return Err(format!( + "invalid passthrough value '{part}': expected 'auto', 'off', \ + or comma-separated list of 'tmux'/'screen' (e.g. 'tmux,tmux')" + )); + } + } + } + if stack.is_empty() { + return Err("empty passthrough value".to_string()); + } + Ok(Some(stack)) + } + } +} #[derive(Parser)] #[command( @@ -32,9 +66,14 @@ struct Cli { #[arg(long, global = true)] animate: bool, - /// SVG external resource access policy [default: none] + /// SVG external resource access policy #[arg(long, value_enum, global = true, default_value_t)] svg_resources: svg::SvgResources, + + /// Multiplexer passthrough: auto, off, or comma-separated tmux/screen layers + /// (e.g. tmux, tmux,tmux, tmux,screen) + #[arg(long, global = true, default_value = "auto")] + passthrough: String, } #[derive(Subcommand)] @@ -221,34 +260,78 @@ fn write_output(data: &[u8], path: Option<&std::path::Path>) -> Result<(), Strin } } -/// Check that it's safe to emit kitty escape sequences. -fn check_terminal(force: bool) -> Result<(), String> { - if force { - return Ok(()); - } - if !io::stdout().is_terminal() { +/// Detect the terminal and multiplexer, check kitty graphics support. +/// +/// Returns the detected mux stack (for passthrough wrapping) or an error if the +/// terminal doesn't support kitty graphics and `--force` is not set. +fn check_terminal( + force: bool, + passthrough: &str, +) -> Result, String> { + if !force && !io::stdout().is_terminal() { return Err( "stdout is not a terminal (use --force to emit escape sequences anyway, \ or use the 'png' subcommand to export as PNG)" .to_string(), ); } - if !kitty::is_supported() { - return Err( - "Terminal does not appear to support kitty graphics protocol \ - (use --force to try anyway)" - .to_string(), - ); + + let parsed = parse_passthrough(passthrough)?; + + // When force is set without an explicit passthrough mode, skip detection + // to avoid the query timeout delay. + if force && parsed.is_none() { + return Ok(vec![]); } - Ok(()) + + // Resolve the mux stack. + let mux_stack = match parsed { + Some(stack) => stack, + None => { + let info = terminal::detect(); + + if !force && !info.supports_kitty_graphics() { + let mut msg = format!( + "Terminal ({}) does not appear to support kitty graphics protocol", + info.terminal + ); + if !info.mux_stack.is_empty() { + let mux_desc: Vec = + info.mux_stack.iter().map(|m| m.to_string()).collect(); + msg.push_str(&format!( + " (detected multiplexer{}: {})", + if info.mux_stack.len() > 1 { "s" } else { "" }, + mux_desc.join(" > "), + )); + if info.mux_stack.iter().any(|m| matches!(m, Mux::Tmux(_))) { + msg.push_str( + "\nHint: ensure the outer terminal supports kitty graphics \ + and add `set -g allow-passthrough on` to your tmux.conf", + ); + } + } + msg.push_str(" (use --force to try anyway)"); + return Err(msg); + } + + info.mux_stack + } + }; + + Ok(mux_stack) } /// Display frames to stdout -- animation if multi-frame, static if single. -fn display_frames(frames: &[(Vec, u32)], out: &mut impl Write) -> Result<(), String> { +fn display_frames( + frames: &[(Vec, u32)], + out: &mut impl Write, + mux_stack: &[Mux], +) -> Result<(), String> { if frames.len() > 1 { - kitty::display_animation(frames, out).map_err(|e| format!("Failed to write: {e}")) + kitty::display_animation(frames, out, mux_stack) + .map_err(|e| format!("Failed to write: {e}")) } else if let Some((png, _)) = frames.first() { - kitty::display_png(png, out).map_err(|e| format!("Failed to write: {e}")) + kitty::display_png(png, out, mux_stack).map_err(|e| format!("Failed to write: {e}")) } else { Ok(()) } @@ -259,14 +342,14 @@ fn run() -> Result<(), String> { match cli.command { Some(Commands::Logo) => { - check_terminal(cli.force)?; + let mux_stack = check_terminal(cli.force, &cli.passthrough)?; let mut stdout = io::stdout().lock(); if cli.animate { let frames = logo::generate_animated_logo(); - display_frames(&frames, &mut stdout)?; + display_frames(&frames, &mut stdout, &mux_stack)?; } else { let png = logo::generate_logo_png(); - kitty::display_png(&png, &mut stdout) + kitty::display_png(&png, &mut stdout, &mux_stack) .map_err(|e| format!("Failed to write: {e}"))?; } writeln!(stdout).map_err(|e| format!("Failed to write: {e}"))?; @@ -295,7 +378,7 @@ fn run() -> Result<(), String> { Ok(()) } None => { - check_terminal(cli.force)?; + let mux_stack = check_terminal(cli.force, &cli.passthrough)?; let mut stdout = io::stdout().lock(); if cli.animate { @@ -306,7 +389,7 @@ fn run() -> Result<(), String> { return Err("No image file specified. Use --help for usage.".to_string()); } }; - display_frames(&frames, &mut stdout)?; + display_frames(&frames, &mut stdout, &mux_stack)?; } else { let png = match cli.file { Some(path) => load_image_as_png(&path, cli.svg_resources)?, @@ -315,7 +398,7 @@ fn run() -> Result<(), String> { return Err("No image file specified. Use --help for usage.".to_string()); } }; - kitty::display_png(&png, &mut stdout) + kitty::display_png(&png, &mut stdout, &mux_stack) .map_err(|e| format!("Failed to write: {e}"))?; } diff --git a/src/svg.rs b/src/svg.rs index 01b390f..23b692b 100644 --- a/src/svg.rs +++ b/src/svg.rs @@ -1,6 +1,7 @@ // SPDX-License-Identifier: Apache-2.0 use resvg::usvg; +use resvg::usvg::fontdb; use std::path::Path; /// Default font size used by mermaid-generated SVGs. @@ -12,6 +13,78 @@ const LINE_HEIGHT: f64 = 1.5; /// 8192x8192 * 4 bytes = 256MB, which is a reasonable upper bound. const MAX_DIMENSION: u32 = 8192; +/// Check if a font family name exists in the font database. +fn has_font_family(db: &fontdb::Database, name: &str) -> bool { + db.faces() + .any(|face| face.families.iter().any(|(f, _)| f == name)) +} + +/// Set a generic font family mapping to the first available font in the list. +/// If none are found, the mapping is left at fontdb's default. +fn set_family_if_available( + db: &mut fontdb::Database, + generic: GenericFamily, + candidates: &[&str], +) { + for &name in candidates { + if has_font_family(db, name) { + match generic { + GenericFamily::SansSerif => db.set_sans_serif_family(name), + GenericFamily::Serif => db.set_serif_family(name), + GenericFamily::Monospace => db.set_monospace_family(name), + } + return; + } + } +} + +enum GenericFamily { + SansSerif, + Serif, + Monospace, +} + +/// Load system fonts and configure generic family mappings with fallbacks. +/// +/// Tries common font families in order, falling back gracefully when +/// specific fonts (e.g. Liberation Sans) aren't installed. +pub fn configure_fonts(opts: &mut usvg::Options) { + opts.fontdb_mut().load_system_fonts(); + set_family_if_available( + opts.fontdb_mut(), + GenericFamily::SansSerif, + &[ + "Liberation Sans", + "DejaVu Sans", + "Helvetica Neue", + "Helvetica", + "Arial", + ], + ); + set_family_if_available( + opts.fontdb_mut(), + GenericFamily::Serif, + &[ + "Liberation Serif", + "DejaVu Serif", + "Georgia", + "Times New Roman", + "Times", + ], + ); + set_family_if_available( + opts.fontdb_mut(), + GenericFamily::Monospace, + &[ + "Liberation Mono", + "DejaVu Sans Mono", + "Menlo", + "Consolas", + "Courier New", + ], + ); +} + /// Controls whether SVGs can load external files via ``. #[derive(Clone, Copy, Debug, Default, PartialEq, clap::ValueEnum)] pub enum SvgResources { @@ -104,12 +177,15 @@ fn strip_tags(s: &str) -> String { inside_tag = false; // Inject separators based on the closing tag name. let tag = tag_buf.trim().to_ascii_lowercase(); - let tag_name = tag + let tag_name_raw = tag .strip_prefix('/') .unwrap_or(&tag) .split_whitespace() .next() .unwrap_or(""); + let tag_name = tag_name_raw + .strip_suffix('/') + .unwrap_or(tag_name_raw); let is_closing = tag.starts_with('/'); match tag_name { //
/
— always a newline (void element, never has a closing tag) @@ -527,10 +603,7 @@ pub fn render_svg_to_png( resolve_string: make_string_resolver(policy), }; - opt.fontdb_mut().load_system_fonts(); - opt.fontdb_mut().set_sans_serif_family("Liberation Sans"); - opt.fontdb_mut().set_serif_family("Liberation Serif"); - opt.fontdb_mut().set_monospace_family("Liberation Mono"); + configure_fonts(&mut opt); let tree = usvg::Tree::from_data(&svg_data, &opt).map_err(|e| format!("Failed to parse SVG: {e}"))?; @@ -723,6 +796,14 @@ mod tests { assert_eq!(lines, vec!["forge-api", "(gRPC gateway)"]); } + #[test] + fn extract_text_br_self_closing_no_space() { + //
without space before / — common in mermaid output + let html = r#"

line1
line2

"#; + let lines = extract_text_lines(html); + assert_eq!(lines, vec!["line1", "line2"]); + } + #[test] fn extract_text_with_entities() { let html = diff --git a/src/terminal.rs b/src/terminal.rs new file mode 100644 index 0000000..27c4b37 --- /dev/null +++ b/src/terminal.rs @@ -0,0 +1,1154 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Terminal and multiplexer detection. +//! +//! Identifies the terminal emulator and any multiplexer layers (tmux, screen) +//! using in-band escape sequence queries (XTVERSION, DA2) with an environment +//! variable fallback. Supports nested multiplexers (e.g. tmux-in-tmux). + +use std::io::{self, IsTerminal}; +use std::time::{Duration, Instant}; + +// ─── Public types ─────────────────────────────────────────── + +/// A detected terminal emulator. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Terminal { + Kitty(Option), + Ghostty(Option), + WezTerm(Option), + Foot(Option), + Konsole(Option), + ITerm2, + Xterm(Option), + Mintty(Option), + Contour(Option), + Vte, + Other(String), + Unknown, +} + +/// A detected multiplexer layer. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Mux { + Tmux(Option), + Screen(Option), + Zellij, +} + +/// Full terminal detection result. +#[derive(Debug, Clone)] +pub struct TerminalInfo { + /// Multiplexer stack, innermost first. + /// E.g. for tmux-in-tmux: `[Tmux, Tmux]` where [0] is the session we're + /// directly inside and [1] is the outer one. + pub mux_stack: Vec, + pub terminal: Terminal, +} + +impl TerminalInfo { + /// Whether the detected terminal supports the kitty graphics protocol. + pub fn supports_kitty_graphics(&self) -> bool { + matches!( + self.terminal, + Terminal::Kitty(_) + | Terminal::Ghostty(_) + | Terminal::WezTerm(_) + | Terminal::Konsole(_) + | Terminal::ITerm2 + ) + } + + /// Whether output needs DCS passthrough wrapping. + #[allow(dead_code)] + pub fn needs_passthrough(&self) -> bool { + self.mux_stack + .iter() + .any(|m| matches!(m, Mux::Tmux(_) | Mux::Screen(_))) + } +} + +impl std::fmt::Display for Terminal { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Terminal::Kitty(v) => write!(f, "kitty{}", ver(v)), + Terminal::Ghostty(v) => write!(f, "Ghostty{}", ver(v)), + Terminal::WezTerm(v) => write!(f, "WezTerm{}", ver(v)), + Terminal::Foot(v) => write!(f, "foot{}", ver(v)), + Terminal::Konsole(v) => write!(f, "Konsole{}", ver(v)), + Terminal::ITerm2 => write!(f, "iTerm2"), + Terminal::Xterm(v) => write!(f, "xterm{}", ver(v)), + Terminal::Mintty(v) => write!(f, "mintty{}", ver(v)), + Terminal::Contour(v) => write!(f, "contour{}", ver(v)), + Terminal::Vte => write!(f, "VTE"), + Terminal::Other(s) => write!(f, "{s}"), + Terminal::Unknown => write!(f, "unknown"), + } + } +} + +impl std::fmt::Display for Mux { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Mux::Tmux(v) => write!(f, "tmux{}", ver(v)), + Mux::Screen(v) => write!(f, "screen{}", ver(v)), + Mux::Zellij => write!(f, "Zellij"), + } + } +} + +fn ver(v: &Option) -> String { + match v { + Some(s) => format!(" {s}"), + None => String::new(), + } +} + +// ─── DCS wrapping (shared with kitty.rs) ──────────────────── + +/// Wrap data for a single multiplexer layer. +/// +/// - **tmux**: double every ESC, wrap in `ESC P tmux ; … ESC \` +/// - **screen**: prefix with `ESC P` (inner ST terminates the DCS) +/// - **Zellij**: return unchanged (transparent) +pub fn wrap_for_mux(data: &[u8], mux: &Mux) -> Vec { + match mux { + Mux::Tmux(_) => { + let mut out = Vec::with_capacity(data.len() * 2 + 10); + out.extend_from_slice(b"\x1bPtmux;"); + for &byte in data { + if byte == 0x1b { + out.push(0x1b); + out.push(0x1b); + } else { + out.push(byte); + } + } + out.extend_from_slice(b"\x1b\\"); + out + } + Mux::Screen(_) => { + let mut out = Vec::with_capacity(data.len() + 2); + out.extend_from_slice(b"\x1bP"); + out.extend_from_slice(data); + out + } + Mux::Zellij => data.to_vec(), + } +} + +/// Wrap data through an entire mux stack (innermost first). +/// +/// Each layer wraps the output of the previous layer. The innermost mux +/// is applied first, then the next layer wraps that result, and so on. +pub fn wrap_for_stack(data: &[u8], stack: &[Mux]) -> Vec { + let mut result = data.to_vec(); + for mux in stack { + result = wrap_for_mux(&result, mux); + } + result +} + +// ─── Escape sequence queries ──────────────────────────────── + +/// XTVERSION query: `ESC [ > 0 q` +const XTVERSION: &[u8] = b"\x1b[>0q"; + +/// DA2 (Secondary Device Attributes) query: `ESC [ > c` +const DA2: &[u8] = b"\x1b[>c"; + +/// Maximum nesting depth to probe (bounds detection time). +const MAX_MUX_DEPTH: usize = 4; + +// ─── Response parsers ─────────────────────────────────────── + +/// Parsed DA2 response parameters. +struct Da2Info { + pp: u32, + pv: u32, +} + +/// Parse an XTVERSION response: `ESC P > | name(version) ST` +/// +/// Returns the terminal (or mux) identified by the name string. +fn parse_xtversion(response: &[u8]) -> Option<(Terminal, Option)> { + // Find the DCS payload start marker ">|" + let marker = response.windows(2).position(|w| w == b">|")?; + let payload_start = marker + 2; + + // Find ST terminator: ESC \ or 0x9C + let payload_end = find_st(response, payload_start)?; + let name = std::str::from_utf8(&response[payload_start..payload_end]).ok()?; + let name = name.trim(); + if name.is_empty() { + return None; + } + + Some(identify_xtversion(name)) +} + +/// Identify terminal/mux from an XTVERSION name string. +fn identify_xtversion(name: &str) -> (Terminal, Option) { + let lower = name.to_ascii_lowercase(); + + if lower.starts_with("tmux") { + let ver = extract_version_space(name); + return (Terminal::Unknown, Some(Mux::Tmux(ver))); + } + if lower.starts_with("kitty") { + return (Terminal::Kitty(extract_version_parens(name)), None); + } + if lower.starts_with("ghostty") { + return (Terminal::Ghostty(extract_version_parens(name)), None); + } + if lower.starts_with("wezterm") { + return (Terminal::WezTerm(extract_version_space(name)), None); + } + if lower.starts_with("foot") { + return (Terminal::Foot(extract_version_parens(name)), None); + } + if lower.starts_with("xterm") { + return (Terminal::Xterm(extract_version_parens(name)), None); + } + if lower.starts_with("contour") { + return (Terminal::Contour(extract_version_parens(name)), None); + } + if lower.starts_with("mintty") { + return (Terminal::Mintty(extract_version_space(name)), None); + } + + (Terminal::Other(name.to_string()), None) +} + +/// Extract version from "name(version)" format. +fn extract_version_parens(name: &str) -> Option { + let start = name.find('(')?; + let end = name.find(')')?; + if end > start + 1 { + Some(name[start + 1..end].to_string()) + } else { + None + } +} + +/// Extract version from "name version" format (everything after first space). +fn extract_version_space(name: &str) -> Option { + let pos = name.find(' ')?; + let ver = name[pos + 1..].trim(); + if ver.is_empty() { None } else { Some(ver.to_string()) } +} + +/// Find the String Terminator (ST) starting from `from`. +/// ST is either ESC `\` (two bytes: 0x1B 0x5C) or the 8-bit form 0x9C. +fn find_st(data: &[u8], from: usize) -> Option { + let mut i = from; + while i < data.len() { + if data[i] == 0x9c { + return Some(i); + } + if data[i] == 0x1b && i + 1 < data.len() && data[i + 1] == b'\\' { + return Some(i); + } + i += 1; + } + None +} + +/// Parse a DA2 response: `ESC [ > Pp ; Pv ; Pc c` +fn parse_da2(response: &[u8]) -> Option { + let start = response.windows(3).position(|w| w == b"\x1b[>")?; + let params_start = start + 3; + + let end = response[params_start..].iter().position(|&b| b == b'c')?; + let params_str = std::str::from_utf8(&response[params_start..params_start + end]).ok()?; + + let parts: Vec<&str> = params_str.split(';').collect(); + if parts.len() < 2 { + return None; + } + + let pp = parts[0].trim().parse().ok()?; + let pv = parts[1].trim().parse().ok()?; + Some(Da2Info { pp, pv }) +} + +/// Map DA2 parameters to a terminal/mux identity. +fn terminal_from_da2(info: &Da2Info) -> (Terminal, Option) { + match info.pp { + 84 => (Terminal::Unknown, Some(Mux::Tmux(None))), + 83 => (Terminal::Unknown, Some(Mux::Screen(None))), + 1 if info.pv >= 4000 => (Terminal::Kitty(Some(format!("{}", info.pv / 1000))), None), + 41 => (Terminal::Xterm(Some(info.pv.to_string())), None), + 65 => (Terminal::Vte, None), + 77 => (Terminal::Mintty(None), None), + _ => (Terminal::Unknown, None), + } +} + +// ─── In-band detection (querier abstraction) ──────────────── + +/// Trait for sending terminal queries and receiving responses. +/// Allows mocking in tests. +trait TerminalQuerier { + fn query(&mut self, request: &[u8], timeout: Duration) -> Option>; +} + +/// Identify what's at the current layer: send XTVERSION, fall back to DA2. +/// Returns (terminal, optional mux detected at this layer). +fn identify_layer(q: &mut impl TerminalQuerier, query_bytes: &[u8], da2_bytes: &[u8], timeout: Duration) -> Option<(Terminal, Option)> { + // Try XTVERSION + if let Some(resp) = q.query(query_bytes, timeout) { + if let Some(result) = parse_xtversion(&resp) { + return Some(result); + } + } + // Try DA2 + if let Some(resp) = q.query(da2_bytes, timeout) { + if let Some(info) = parse_da2(&resp) { + return Some(terminal_from_da2(&info)); + } + } + None +} + +/// Run the full in-band detection algorithm using a querier. +/// Recursively probes through mux layers to find the outer terminal. +fn detect_inband(q: &mut impl TerminalQuerier) -> TerminalInfo { + let timeout = Duration::from_millis(1500); + let passthrough_timeout = Duration::from_millis(2000); + + // Identify the immediate layer (no passthrough wrapping) + let Some((terminal, mux)) = identify_layer(q, XTVERSION, DA2, timeout) else { + return TerminalInfo { + mux_stack: vec![], + terminal: Terminal::Unknown, + }; + }; + + let Some(first_mux) = mux else { + // Direct terminal, no mux + return TerminalInfo { + mux_stack: vec![], + terminal, + }; + }; + + // We're inside at least one mux. Probe outward recursively. + let mut stack = vec![first_mux]; + probe_outer(q, &mut stack, passthrough_timeout); + + // Query through the full discovered stack to identify the outer terminal. + let xt = wrap_for_stack(XTVERSION, &stack); + let da = wrap_for_stack(DA2, &stack); + let terminal = if let Some((term, mux)) = identify_layer(q, &xt, &da, passthrough_timeout) { + if let Some(outer_mux) = mux { + // Even more nesting beyond what probe_outer found. + if stack.len() < MAX_MUX_DEPTH { + stack.push(outer_mux); + } + Terminal::Unknown + } else { + term + } + } else { + Terminal::Unknown + }; + + TerminalInfo { + mux_stack: stack, + terminal, + } +} + +/// Recursively probe through mux layers to discover nesting. +/// `stack` already contains the first detected mux. We wrap queries through +/// the current stack and check if the response reveals another mux layer. +fn probe_outer(q: &mut impl TerminalQuerier, stack: &mut Vec, timeout: Duration) { + while stack.len() < MAX_MUX_DEPTH { + let xt = wrap_for_stack(XTVERSION, stack); + let da = wrap_for_stack(DA2, stack); + + let Some((_, mux)) = identify_layer(q, &xt, &da, timeout) else { + break; + }; + + match mux { + Some(next_mux) => stack.push(next_mux), + None => break, // Found a terminal, not a mux — done + } + } +} + +// ─── Env var fallback ─────────────────────────────────────── + +/// Detect terminal and mux from environment variables alone. +pub fn detect_from_env() -> TerminalInfo { + let mux_stack = detect_mux_env(); + let terminal = detect_terminal_env(); + TerminalInfo { mux_stack, terminal } +} + +fn detect_mux_env() -> Vec { + // Env vars can only detect one layer (the innermost mux sets the var). + if std::env::var_os("TMUX").is_some() { + return vec![Mux::Tmux(None)]; + } + if std::env::var_os("STY").is_some() { + return vec![Mux::Screen(None)]; + } + if std::env::var_os("ZELLIJ").is_some() { + return vec![Mux::Zellij]; + } + vec![] +} + +fn detect_terminal_env() -> Terminal { + if std::env::var_os("KITTY_WINDOW_ID").is_some() { + return Terminal::Kitty(None); + } + if std::env::var_os("KONSOLE_VERSION").is_some() { + return Terminal::Konsole(None); + } + if let Some(prog) = std::env::var_os("TERM_PROGRAM") { + let prog = prog.to_string_lossy(); + match prog.as_ref() { + "kitty" => return Terminal::Kitty(None), + "WezTerm" => return Terminal::WezTerm(None), + "ghostty" | "Ghostty" => return Terminal::Ghostty(None), + "iTerm.app" | "iTerm2" => return Terminal::ITerm2, + _ => {} + } + } + if let Some(term) = std::env::var_os("TERM") { + let term = term.to_string_lossy().to_ascii_lowercase(); + if term.contains("kitty") { + return Terminal::Kitty(None); + } + if term.contains("ghostty") { + return Terminal::Ghostty(None); + } + if term.contains("wezterm") { + return Terminal::WezTerm(None); + } + } + Terminal::Unknown +} + +// ─── Platform I/O: Unix ───────────────────────────────────── + +#[cfg(unix)] +mod tty { + use super::*; + use std::os::unix::io::{AsRawFd, RawFd}; + + /// RAII guard that restores termios settings on drop. + struct RawModeGuard { + fd: RawFd, + original: libc::termios, + } + + impl Drop for RawModeGuard { + fn drop(&mut self) { + unsafe { + libc::tcsetattr(self.fd, libc::TCSANOW, &self.original); + } + } + } + + /// A session for querying the terminal via escape sequences. + pub struct QuerySession { + read_fd: RawFd, + write_fd: RawFd, + _tty_file: Option, + _guard: RawModeGuard, + } + + impl QuerySession { + /// Open a query session. + /// + /// Prefers stdin/stdout when stdin is a terminal. Falls back to + /// `/dev/tty` when stdin is redirected (e.g. piped image data). + pub fn open() -> io::Result { + if io::stdin().is_terminal() { + Self::from_stdin() + } else { + Self::from_dev_tty() + } + } + + fn from_stdin() -> io::Result { + let read_fd = io::stdin().as_raw_fd(); + let write_fd = io::stdout().as_raw_fd(); + let guard = enter_raw_mode(read_fd)?; + Ok(Self { + read_fd, + write_fd, + _tty_file: None, + _guard: guard, + }) + } + + fn from_dev_tty() -> io::Result { + let tty = std::fs::OpenOptions::new() + .read(true) + .write(true) + .open("/dev/tty")?; + let fd = tty.as_raw_fd(); + let guard = enter_raw_mode(fd)?; + Ok(Self { + read_fd: fd, + write_fd: fd, + _tty_file: Some(tty), + _guard: guard, + }) + } + + /// Drain any pending bytes from the read fd. + fn drain(&self) { + let mut byte = [0u8]; + loop { + if !poll_fd(self.read_fd, Duration::ZERO).unwrap_or(false) { + break; + } + let ret = + unsafe { libc::read(self.read_fd, byte.as_mut_ptr().cast(), 1) }; + if ret <= 0 { + break; + } + } + } + + /// Read bytes until the response looks complete or the deadline passes. + fn read_response(&self, timeout: Duration) -> Option> { + let deadline = Instant::now() + timeout; + let mut buf = Vec::with_capacity(128); + + loop { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + break; + } + if !poll_fd(self.read_fd, remaining).unwrap_or(false) { + break; + } + let mut byte = [0u8]; + let ret = + unsafe { libc::read(self.read_fd, byte.as_mut_ptr().cast(), 1) }; + if ret <= 0 { + break; + } + buf.push(byte[0]); + if is_response_complete(&buf) { + break; + } + } + + if buf.is_empty() { None } else { Some(buf) } + } + } + + impl TerminalQuerier for QuerySession { + fn query(&mut self, request: &[u8], timeout: Duration) -> Option> { + self.drain(); + let ret = unsafe { + libc::write(self.write_fd, request.as_ptr().cast(), request.len()) + }; + if ret < 0 { + return None; + } + self.read_response(timeout) + } + } + + fn enter_raw_mode(fd: RawFd) -> io::Result { + let mut original: libc::termios = unsafe { std::mem::zeroed() }; + if unsafe { libc::tcgetattr(fd, &mut original) } != 0 { + return Err(io::Error::last_os_error()); + } + let mut raw = original; + unsafe { libc::cfmakeraw(&mut raw) }; + if unsafe { libc::tcsetattr(fd, libc::TCSANOW, &raw) } != 0 { + return Err(io::Error::last_os_error()); + } + Ok(RawModeGuard { fd, original }) + } + + fn poll_fd(fd: RawFd, timeout: Duration) -> io::Result { + let mut pfd = libc::pollfd { + fd, + events: libc::POLLIN, + revents: 0, + }; + let timeout_ms = timeout.as_millis().min(i32::MAX as u128) as libc::c_int; + let ret = unsafe { libc::poll(&mut pfd, 1, timeout_ms) }; + if ret < 0 { + let err = io::Error::last_os_error(); + if err.kind() == io::ErrorKind::Interrupted { + return Ok(false); + } + return Err(err); + } + Ok(ret > 0 && (pfd.revents & libc::POLLIN) != 0) + } + + /// Detect using in-band queries, falling back to env vars. + pub fn detect() -> TerminalInfo { + match QuerySession::open() { + Ok(mut session) => { + let info = detect_inband(&mut session); + // If in-band detection found mux(es) but not the terminal, + // try env vars for the terminal identity. + if info.terminal == Terminal::Unknown { + let env = detect_from_env(); + TerminalInfo { + mux_stack: if info.mux_stack.is_empty() { + env.mux_stack + } else { + info.mux_stack + }, + terminal: if env.terminal != Terminal::Unknown { + env.terminal + } else { + info.terminal + }, + } + } else if info.mux_stack.is_empty() { + // In-band found terminal but no mux — check env for mux + let env_mux = detect_mux_env(); + TerminalInfo { + mux_stack: env_mux, + terminal: info.terminal, + } + } else { + info + } + } + Err(_) => detect_from_env(), + } + } +} + +/// Check whether a response buffer contains a complete terminal response. +fn is_response_complete(buf: &[u8]) -> bool { + let len = buf.len(); + if len < 2 { + return false; + } + + // DCS / XTVERSION response ends with ESC \ (ST) + if buf[len - 2] == 0x1b && buf[len - 1] == b'\\' { + return true; + } + + // 8-bit ST + if buf[len - 1] == 0x9c { + return true; + } + + // DA2 response: ESC [ > ... c + if buf[len - 1] == b'c' && len >= 6 { + return buf.windows(3).any(|w| w == b"\x1b[>"); + } + + false +} + +// ─── Public API ───────────────────────────────────────────── + +/// Detect the terminal emulator and any multiplexer layers. +/// +/// Uses in-band escape sequence queries when a terminal is available, +/// falling back to environment variables. +pub fn detect() -> TerminalInfo { + #[cfg(unix)] + { + tty::detect() + } + #[cfg(not(unix))] + { + detect_from_env() + } +} + +// ─── Tests ────────────────────────────────────────────────── + +#[cfg(test)] +mod tests { + use super::*; + + // ── Parser tests ──────────────────────────────────────── + + #[test] + fn xtversion_kitty() { + let resp = b"\x1bP>|kitty(0.26.5)\x1b\\"; + let (term, mux) = parse_xtversion(resp).unwrap(); + assert_eq!(term, Terminal::Kitty(Some("0.26.5".into()))); + assert!(mux.is_none()); + } + + #[test] + fn xtversion_tmux() { + let resp = b"\x1bP>|tmux 3.3a\x1b\\"; + let (term, mux) = parse_xtversion(resp).unwrap(); + assert_eq!(term, Terminal::Unknown); + assert_eq!(mux, Some(Mux::Tmux(Some("3.3a".into())))); + } + + #[test] + fn xtversion_ghostty() { + let resp = b"\x1bP>|Ghostty(1.0.0)\x1b\\"; + let (term, mux) = parse_xtversion(resp).unwrap(); + assert_eq!(term, Terminal::Ghostty(Some("1.0.0".into()))); + assert!(mux.is_none()); + } + + #[test] + fn xtversion_wezterm() { + let resp = b"\x1bP>|WezTerm 20230408-112425-69ae8472\x1b\\"; + let (term, _) = parse_xtversion(resp).unwrap(); + assert_eq!( + term, + Terminal::WezTerm(Some("20230408-112425-69ae8472".into())) + ); + } + + #[test] + fn xtversion_foot() { + let resp = b"\x1bP>|foot(1.13.1)\x1b\\"; + let (term, _) = parse_xtversion(resp).unwrap(); + assert_eq!(term, Terminal::Foot(Some("1.13.1".into()))); + } + + #[test] + fn xtversion_xterm() { + let resp = b"\x1bP>|xterm(351)\x1b\\"; + let (term, _) = parse_xtversion(resp).unwrap(); + assert_eq!(term, Terminal::Xterm(Some("351".into()))); + } + + #[test] + fn xtversion_mintty() { + let resp = b"\x1bP>|mintty 3.6.4\x1b\\"; + let (term, _) = parse_xtversion(resp).unwrap(); + assert_eq!(term, Terminal::Mintty(Some("3.6.4".into()))); + } + + #[test] + fn xtversion_contour() { + let resp = b"\x1bP>|contour(0.3.12)\x1b\\"; + let (term, _) = parse_xtversion(resp).unwrap(); + assert_eq!(term, Terminal::Contour(Some("0.3.12".into()))); + } + + #[test] + fn xtversion_8bit_st() { + let resp = b"\x1bP>|foot(1.13.1)\x9c"; + let (term, _) = parse_xtversion(resp).unwrap(); + assert_eq!(term, Terminal::Foot(Some("1.13.1".into()))); + } + + #[test] + fn xtversion_unknown_terminal() { + let resp = b"\x1bP>|SomeFutureTerminal 2.0\x1b\\"; + let (term, mux) = parse_xtversion(resp).unwrap(); + assert_eq!(term, Terminal::Other("SomeFutureTerminal 2.0".into())); + assert!(mux.is_none()); + } + + #[test] + fn xtversion_garbage() { + assert!(parse_xtversion(b"not a valid response").is_none()); + assert!(parse_xtversion(b"").is_none()); + assert!(parse_xtversion(b"\x1bP>|\x1b\\").is_none()); + } + + #[test] + fn da2_tmux() { + let resp = b"\x1b[>84;0;0c"; + let info = parse_da2(resp).unwrap(); + assert_eq!(info.pp, 84); + let (_, mux) = terminal_from_da2(&info); + assert!(matches!(mux, Some(Mux::Tmux(_)))); + } + + #[test] + fn da2_screen() { + let resp = b"\x1b[>83;40801;0c"; + let info = parse_da2(resp).unwrap(); + let (_, mux) = terminal_from_da2(&info); + assert!(matches!(mux, Some(Mux::Screen(_)))); + } + + #[test] + fn da2_kitty() { + let resp = b"\x1b[>1;4000;29c"; + let info = parse_da2(resp).unwrap(); + let (term, mux) = terminal_from_da2(&info); + assert!(matches!(term, Terminal::Kitty(_))); + assert!(mux.is_none()); + } + + #[test] + fn da2_xterm() { + let resp = b"\x1b[>41;351;0c"; + let info = parse_da2(resp).unwrap(); + let (term, _) = terminal_from_da2(&info); + assert!(matches!(term, Terminal::Xterm(_))); + } + + #[test] + fn da2_vte() { + let resp = b"\x1b[>65;6700;1c"; + let info = parse_da2(resp).unwrap(); + let (term, _) = terminal_from_da2(&info); + assert_eq!(term, Terminal::Vte); + } + + #[test] + fn da2_mintty() { + let resp = b"\x1b[>77;30105;0c"; + let info = parse_da2(resp).unwrap(); + let (term, _) = terminal_from_da2(&info); + assert!(matches!(term, Terminal::Mintty(_))); + } + + #[test] + fn da2_garbage() { + assert!(parse_da2(b"not a valid response").is_none()); + assert!(parse_da2(b"").is_none()); + assert!(parse_da2(b"\x1b[>c").is_none()); + } + + // ── Response completeness ─────────────────────────────── + + #[test] + fn response_complete_xtversion() { + assert!(is_response_complete(b"\x1bP>|kitty(0.26.5)\x1b\\")); + } + + #[test] + fn response_complete_8bit_st() { + assert!(is_response_complete(b"\x1bP>|foot(1.0)\x9c")); + } + + #[test] + fn response_complete_da2() { + assert!(is_response_complete(b"\x1b[>1;4000;29c")); + } + + #[test] + fn response_incomplete() { + assert!(!is_response_complete(b"\x1bP>|kit")); + assert!(!is_response_complete(b"\x1b[>1;40")); + assert!(!is_response_complete(b"")); + assert!(!is_response_complete(b"\x1b")); + } + + // ── Wrapping ──────────────────────────────────────────── + + #[test] + fn wrap_for_mux_tmux() { + let data = b"\x1b[>0q"; + let wrapped = wrap_for_mux(data, &Mux::Tmux(None)); + // ESC P tmux ; ESC ESC [ > 0 q ESC \ + assert_eq!(wrapped, b"\x1bPtmux;\x1b\x1b[>0q\x1b\\"); + } + + #[test] + fn wrap_for_mux_screen() { + let data = b"\x1b[>0q"; + let wrapped = wrap_for_mux(data, &Mux::Screen(None)); + assert_eq!(wrapped, b"\x1bP\x1b[>0q"); + } + + #[test] + fn wrap_for_stack_double_tmux() { + let data = b"\x1b[>0q"; + let stack = vec![Mux::Tmux(None), Mux::Tmux(None)]; + let wrapped = wrap_for_stack(data, &stack); + // Inner wrap: ESC doubled once + // Outer wrap: all ESCs in the inner result doubled again + // Original ESC -> 2 ESC (inner) -> 4 ESC (outer) + let inner = wrap_for_mux(data, &Mux::Tmux(None)); + let expected = wrap_for_mux(&inner, &Mux::Tmux(None)); + assert_eq!(wrapped, expected); + } + + #[test] + fn wrap_for_stack_tmux_in_screen() { + let data = b"\x1b[>0q"; + let stack = vec![Mux::Tmux(None), Mux::Screen(None)]; + let wrapped = wrap_for_stack(data, &stack); + let inner = wrap_for_mux(data, &Mux::Tmux(None)); + let expected = wrap_for_mux(&inner, &Mux::Screen(None)); + assert_eq!(wrapped, expected); + } + + #[test] + fn wrap_for_stack_empty() { + let data = b"\x1b[>0q"; + let wrapped = wrap_for_stack(data, &[]); + assert_eq!(wrapped, data); + } + + #[test] + fn wrap_for_mux_zellij_transparent() { + let data = b"\x1b[>0q"; + let wrapped = wrap_for_mux(data, &Mux::Zellij); + assert_eq!(wrapped, data); + } + + // ── Mock querier for detection algorithm ──────────────── + + struct MockQuerier { + responses: Vec<(Vec, Option>)>, + } + + impl MockQuerier { + fn new(responses: Vec<(Vec, Option>)>) -> Self { + Self { responses } + } + } + + impl TerminalQuerier for MockQuerier { + fn query(&mut self, request: &[u8], _timeout: Duration) -> Option> { + for (req, resp) in &self.responses { + if req == request { + return resp.clone(); + } + } + None + } + } + + #[test] + fn detect_direct_kitty_via_xtversion() { + let mut q = MockQuerier::new(vec![( + XTVERSION.to_vec(), + Some(b"\x1bP>|kitty(0.35.0)\x1b\\".to_vec()), + )]); + let info = detect_inband(&mut q); + assert!(matches!(info.terminal, Terminal::Kitty(_))); + assert!(info.mux_stack.is_empty()); + } + + #[test] + fn detect_tmux_with_kitty_outer() { + // XTVERSION returns tmux, then XTVERSION-through-tmux returns tmux again + // (probe_outer loop), then XTVERSION-through-2-tmux returns kitty + // Actually: XTVERSION returns tmux. Then probe_outer wraps XTVERSION + // through [tmux] and gets kitty (no more mux). Then detect_inband + // wraps through full stack and gets kitty. + let xt_through_tmux = wrap_for_stack(XTVERSION, &[Mux::Tmux(None)]); + let mut q = MockQuerier::new(vec![ + ( + XTVERSION.to_vec(), + Some(b"\x1bP>|tmux 3.3a\x1b\\".to_vec()), + ), + // probe_outer: XTVERSION through 1 tmux -> kitty (terminal, not mux) + ( + xt_through_tmux.clone(), + Some(b"\x1bP>|kitty(0.35.0)\x1b\\".to_vec()), + ), + // detect_inband final query through full stack -> kitty + ( + xt_through_tmux, + Some(b"\x1bP>|kitty(0.35.0)\x1b\\".to_vec()), + ), + ]); + let info = detect_inband(&mut q); + assert_eq!(info.mux_stack.len(), 1); + assert!(matches!(info.mux_stack[0], Mux::Tmux(_))); + assert!(matches!(info.terminal, Terminal::Kitty(_))); + } + + #[test] + fn detect_nested_tmux_with_kitty_outer() { + let xt_1 = wrap_for_stack(XTVERSION, &[Mux::Tmux(None)]); + let xt_2 = wrap_for_stack(XTVERSION, &[Mux::Tmux(None), Mux::Tmux(None)]); + let mut q = MockQuerier::new(vec![ + // Layer 0: XTVERSION -> tmux + ( + XTVERSION.to_vec(), + Some(b"\x1bP>|tmux 3.4\x1b\\".to_vec()), + ), + // probe_outer through 1 tmux -> another tmux + ( + xt_1.clone(), + Some(b"\x1bP>|tmux 3.3a\x1b\\".to_vec()), + ), + // probe_outer through 2 tmux -> kitty (terminal) + ( + xt_2.clone(), + Some(b"\x1bP>|kitty(0.35.0)\x1b\\".to_vec()), + ), + // detect_inband final query through full stack -> kitty + ( + xt_2, + Some(b"\x1bP>|kitty(0.35.0)\x1b\\".to_vec()), + ), + ]); + let info = detect_inband(&mut q); + assert_eq!(info.mux_stack.len(), 2); + assert!(matches!(info.mux_stack[0], Mux::Tmux(_))); + assert!(matches!(info.mux_stack[1], Mux::Tmux(_))); + assert!(matches!(info.terminal, Terminal::Kitty(_))); + } + + #[test] + fn detect_tmux_in_screen_with_ghostty_outer() { + let xt_tmux = wrap_for_stack(XTVERSION, &[Mux::Tmux(None)]); + let da_tmux = wrap_for_stack(DA2, &[Mux::Tmux(None)]); + let xt_both = wrap_for_stack(XTVERSION, &[Mux::Tmux(None), Mux::Screen(None)]); + + let mut q = MockQuerier::new(vec![ + // XTVERSION -> tmux (innermost) + ( + XTVERSION.to_vec(), + Some(b"\x1bP>|tmux 3.4\x1b\\".to_vec()), + ), + // Through tmux: XTVERSION times out, DA2 -> screen + (xt_tmux.clone(), None), + ( + da_tmux.clone(), + Some(b"\x1b[>83;40801;0c".to_vec()), + ), + // Through tmux+screen: XTVERSION -> Ghostty + ( + xt_both.clone(), + Some(b"\x1bP>|Ghostty(1.0.0)\x1b\\".to_vec()), + ), + // Final query through stack -> Ghostty + ( + xt_both, + Some(b"\x1bP>|Ghostty(1.0.0)\x1b\\".to_vec()), + ), + ]); + let info = detect_inband(&mut q); + assert_eq!(info.mux_stack.len(), 2); + assert!(matches!(info.mux_stack[0], Mux::Tmux(_))); + assert!(matches!(info.mux_stack[1], Mux::Screen(_))); + assert!(matches!(info.terminal, Terminal::Ghostty(_))); + } + + #[test] + fn detect_screen_via_da2() { + let xt_screen = wrap_for_stack(XTVERSION, &[Mux::Screen(None)]); + + let mut q = MockQuerier::new(vec![ + (XTVERSION.to_vec(), None), + (DA2.to_vec(), Some(b"\x1b[>83;40801;0c".to_vec())), + // Through screen -> kitty + ( + xt_screen.clone(), + Some(b"\x1bP>|kitty(0.30.0)\x1b\\".to_vec()), + ), + // Final query + ( + xt_screen, + Some(b"\x1bP>|kitty(0.30.0)\x1b\\".to_vec()), + ), + ]); + let info = detect_inband(&mut q); + assert_eq!(info.mux_stack.len(), 1); + assert!(matches!(info.mux_stack[0], Mux::Screen(_))); + assert!(matches!(info.terminal, Terminal::Kitty(_))); + } + + #[test] + fn detect_direct_kitty_via_da2() { + let mut q = MockQuerier::new(vec![ + (XTVERSION.to_vec(), None), + (DA2.to_vec(), Some(b"\x1b[>1;4000;29c".to_vec())), + ]); + let info = detect_inband(&mut q); + assert!(matches!(info.terminal, Terminal::Kitty(_))); + assert!(info.mux_stack.is_empty()); + } + + #[test] + fn detect_both_timeout_returns_unknown() { + let mut q = MockQuerier::new(vec![ + (XTVERSION.to_vec(), None), + (DA2.to_vec(), None), + ]); + let info = detect_inband(&mut q); + assert_eq!(info.terminal, Terminal::Unknown); + assert!(info.mux_stack.is_empty()); + } + + #[test] + fn detect_tmux_outer_unknown_falls_through() { + let xt_tmux = wrap_for_stack(XTVERSION, &[Mux::Tmux(None)]); + let da_tmux = wrap_for_stack(DA2, &[Mux::Tmux(None)]); + let mut q = MockQuerier::new(vec![ + ( + XTVERSION.to_vec(), + Some(b"\x1bP>|tmux 3.4\x1b\\".to_vec()), + ), + // probe_outer and final query all time out + (xt_tmux, None), + (da_tmux, None), + ]); + let info = detect_inband(&mut q); + assert_eq!(info.mux_stack.len(), 1); + assert!(matches!(info.mux_stack[0], Mux::Tmux(_))); + assert_eq!(info.terminal, Terminal::Unknown); + } + + // ── TerminalInfo methods ──────────────────────────────── + + #[test] + fn kitty_supports_graphics() { + let info = TerminalInfo { + mux_stack: vec![], + terminal: Terminal::Kitty(None), + }; + assert!(info.supports_kitty_graphics()); + } + + #[test] + fn unknown_does_not_support_graphics() { + let info = TerminalInfo { + mux_stack: vec![], + terminal: Terminal::Unknown, + }; + assert!(!info.supports_kitty_graphics()); + } + + #[test] + fn tmux_needs_passthrough() { + let info = TerminalInfo { + mux_stack: vec![Mux::Tmux(None)], + terminal: Terminal::Kitty(None), + }; + assert!(info.needs_passthrough()); + } + + #[test] + fn nested_tmux_needs_passthrough() { + let info = TerminalInfo { + mux_stack: vec![Mux::Tmux(None), Mux::Tmux(None)], + terminal: Terminal::Kitty(None), + }; + assert!(info.needs_passthrough()); + } + + #[test] + fn zellij_does_not_need_passthrough() { + let info = TerminalInfo { + mux_stack: vec![Mux::Zellij], + terminal: Terminal::Kitty(None), + }; + assert!(!info.needs_passthrough()); + } + + #[test] + fn no_mux_does_not_need_passthrough() { + let info = TerminalInfo { + mux_stack: vec![], + terminal: Terminal::Kitty(None), + }; + assert!(!info.needs_passthrough()); + } +} diff --git a/test/visual-test.sh b/test/visual-test.sh new file mode 100755 index 0000000..6007881 --- /dev/null +++ b/test/visual-test.sh @@ -0,0 +1,182 @@ +#!/usr/bin/env bash +# Visual regression test for kittyview SVG text rendering. +# +# Run this in a kitty-graphics-capable terminal (kitty, ghostty, wezterm, etc.) +# to verify that text renders correctly in SVG-based images. +# +# Usage: +# ./test/visual-test.sh [path-to-kittyview] +# +# The script displays several test images and asks for visual confirmation. + +set -euo pipefail + +KITTYVIEW="${1:-cargo run --release --}" +PASS=0 +FAIL=0 +SKIP=0 + +# Create a temp directory for SVG test files (macOS mktemp doesn't support suffixes) +TMPDIR_TEST=$(mktemp -d) +trap 'rm -rf "$TMPDIR_TEST"' EXIT + +# Colors for output +RED='\033[0;31m' +GREEN='\033[0;32m' +YELLOW='\033[0;33m' +BOLD='\033[1m' +RESET='\033[0m' + +ask_yn() { + local prompt="$1" + while true; do + printf "${BOLD}%s [y/n]: ${RESET}" "$prompt" + read -r -n 1 answer + echo + case "$answer" in + [yY]) return 0 ;; + [nN]) return 1 ;; + *) echo "Please answer y or n." ;; + esac + done +} + +run_test() { + local name="$1" + local description="$2" + shift 2 + + echo + printf "${BOLD}=== Test: %s ===${RESET}\n" "$name" + echo "$description" + echo + + if ! eval "$@" 2>/dev/null; then + printf "${YELLOW}SKIP${RESET} - command failed (missing dependencies or unsupported terminal)\n" + SKIP=$((SKIP + 1)) + return + fi + + echo + if ask_yn "Does the image above look correct?"; then + printf "${GREEN}PASS${RESET}\n" + PASS=$((PASS + 1)) + else + printf "${RED}FAIL${RESET}\n" + FAIL=$((FAIL + 1)) + fi +} + +# ── Test 1: Animated logo (SVG text in speech bubble) ────────── + +run_test "animated-logo" \ + "You should see a pixel-art kitten with a white speech bubble. +The bubble should contain: + - \"kittyview\" in bold dark purple text + - \"github.com/gominimal/kittyview\" in lighter purple text below" \ + "$KITTYVIEW logo --animate" + +# ── Test 2: Static logo (pixel art, no SVG text) ────────────── + +run_test "static-logo" \ + "You should see a small pixel-art kitten face (purple/pink). +No text expected - this tests basic kitty graphics protocol." \ + "$KITTYVIEW logo" + +# ── Test 3: SVG with text (generated inline) ────────────────── + +SVG_TEXT_FILE="$TMPDIR_TEST/text-test.svg" +cat > "$SVG_TEXT_FILE" << 'SVGEOF' + + + SVG Text Test + If you can read this, fonts work! + monospace: 0123456789 + +SVGEOF + +run_test "svg-text" \ + "You should see a light gray box containing three lines of text: + - \"SVG Text Test\" (bold, dark) + - \"If you can read this, fonts work!\" (medium gray) + - \"monospace: 0123456789\" (light gray, monospace font)" \ + "$KITTYVIEW '$SVG_TEXT_FILE'" + +# ── Test 4: Mermaid-style SVG with foreignObject ───────────── + +SVG_FOREIGN_FILE="$TMPDIR_TEST/foreign-test.svg" +cat > "$SVG_FOREIGN_FILE" << 'SVGEOF' + + + + + +
+

Node A

+
+
+
+ + + +
+

Node B

+
+
+
+ +
+SVGEOF + +run_test "foreignObject-text" \ + "You should see two purple rounded boxes stacked vertically: + - Top box: text \"Node A\" centered + - Bottom box: text \"Node B\" centered + - A line connecting them +(Note: text is converted from foreignObject -- tests the mermaid conversion pipeline)" \ + "$KITTYVIEW '$SVG_FOREIGN_FILE'" + +# ── Test 5: SVG with
in foreignObject ────────────────── + +SVG_BR_FILE="$TMPDIR_TEST/br-test.svg" +cat > "$SVG_BR_FILE" << 'SVGEOF' + + + + + +
+

line one
line two
line three

+
+
+
+
+SVGEOF + +run_test "br-tag-multiline" \ + "You should see a green rounded box containing THREE lines of text: + - \"line one\" + - \"line two\" + - \"line three\" +(Tests
handling in foreignObject conversion)" \ + "$KITTYVIEW '$SVG_BR_FILE'" + +# ── Summary ────────────────────────────────────────────────── + +echo +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" +printf "${BOLD}Results:${RESET} " +printf "${GREEN}%d passed${RESET}, " "$PASS" +printf "${RED}%d failed${RESET}, " "$FAIL" +printf "${YELLOW}%d skipped${RESET}\n" "$SKIP" +echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" + +if [ "$FAIL" -gt 0 ]; then + echo + echo "If text is missing from SVG images, possible causes:" + echo " - No sans-serif font installed (need one of: Liberation Sans," + echo " DejaVu Sans, Helvetica, Arial)" + echo " - Terminal does not support kitty graphics protocol" + echo " - Running inside tmux without 'set -g allow-passthrough on'" + exit 1 +fi From 635bd39aa8c0fcaf1441e0737822fc5cab8f7cc1 Mon Sep 17 00:00:00 2001 From: msample <4896732+msample@users.noreply.github.com> Date: Fri, 3 Apr 2026 22:17:33 -0700 Subject: [PATCH 2/2] fmt & clippy --- src/kitty.rs | 18 +++++------ src/logo.rs | 9 ++++-- src/main.rs | 25 +++++++-------- src/svg.rs | 17 +++------- src/terminal.rs | 83 +++++++++++++++++-------------------------------- 5 files changed, 59 insertions(+), 93 deletions(-) diff --git a/src/kitty.rs b/src/kitty.rs index c1750e9..68541fa 100644 --- a/src/kitty.rs +++ b/src/kitty.rs @@ -56,11 +56,7 @@ fn write_frame_data( } /// Display a single PNG image via the kitty graphics protocol. -pub fn display_png( - png_data: &[u8], - out: &mut impl Write, - mux_stack: &[Mux], -) -> io::Result<()> { +pub fn display_png(png_data: &[u8], out: &mut impl Write, mux_stack: &[Mux]) -> io::Result<()> { let mut buf = Vec::with_capacity(png_data.len() * 2); write_frame_data(&mut buf, png_data, "a=T,f=100", mux_stack)?; out.write_all(&buf)?; @@ -85,7 +81,12 @@ pub fn display_animation( const ID: u32 = 1; // Base frame (frame 1) - write_frame_data(&mut buf, &frames[0].0, &format!("a=T,f=100,i={ID},q=2"), mux_stack)?; + write_frame_data( + &mut buf, + &frames[0].0, + &format!("a=T,f=100,i={ID},q=2"), + mux_stack, + )?; // Additional frames for (i, (png_data, delay_ms)) in frames.iter().enumerate().skip(1) { @@ -225,10 +226,7 @@ mod tests { #[test] fn tmux_animation_start_wrapped() { - let frames = vec![ - (b"f1".to_vec(), 100u32), - (b"f2".to_vec(), 150), - ]; + let frames = vec![(b"f1".to_vec(), 100u32), (b"f2".to_vec(), 150)]; let mut out = Vec::new(); let stack = [Mux::Tmux(None)]; display_animation(&frames, &mut out, &stack).unwrap(); diff --git a/src/logo.rs b/src/logo.rs index 3b1e49e..261b166 100644 --- a/src/logo.rs +++ b/src/logo.rs @@ -235,9 +235,12 @@ mod tests { let img = image::load_from_memory(&frames[0].0).unwrap().to_rgba8(); // The speech bubble text ("kittyview") is dark purple (#2D1B69). // Check for dark pixels in the right half of the image (where the bubble is). - let dark_in_bubble = img.enumerate_pixels().filter(|(x, _, p)| { - *x > 150 && p.0[0] < 80 && p.0[1] < 80 && p.0[2] < 120 && p.0[3] > 200 - }).count(); + let dark_in_bubble = img + .enumerate_pixels() + .filter(|(x, _, p)| { + *x > 150 && p.0[0] < 80 && p.0[1] < 80 && p.0[2] < 120 && p.0[3] > 200 + }) + .count(); assert!( dark_in_bubble > 50, "speech bubble should contain visible text pixels (got {dark_in_bubble})" diff --git a/src/main.rs b/src/main.rs index 3d8172f..936a8c5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -264,10 +264,7 @@ fn write_output(data: &[u8], path: Option<&std::path::Path>) -> Result<(), Strin /// /// Returns the detected mux stack (for passthrough wrapping) or an error if the /// terminal doesn't support kitty graphics and `--force` is not set. -fn check_terminal( - force: bool, - passthrough: &str, -) -> Result, String> { +fn check_terminal(force: bool, passthrough: &str) -> Result, String> { if !force && !io::stdout().is_terminal() { return Err( "stdout is not a terminal (use --force to emit escape sequences anyway, \ @@ -408,6 +405,16 @@ fn run() -> Result<(), String> { } } +fn main() -> ExitCode { + match run() { + Ok(()) => ExitCode::SUCCESS, + Err(msg) => { + eprintln!("Error: {msg}"); + ExitCode::FAILURE + } + } +} + #[cfg(test)] mod tests { use super::*; @@ -452,13 +459,3 @@ mod tests { assert!(!is_svg_data(b"")); } } - -fn main() -> ExitCode { - match run() { - Ok(()) => ExitCode::SUCCESS, - Err(msg) => { - eprintln!("Error: {msg}"); - ExitCode::FAILURE - } - } -} diff --git a/src/svg.rs b/src/svg.rs index 23b692b..aa69cc1 100644 --- a/src/svg.rs +++ b/src/svg.rs @@ -21,11 +21,7 @@ fn has_font_family(db: &fontdb::Database, name: &str) -> bool { /// Set a generic font family mapping to the first available font in the list. /// If none are found, the mapping is left at fontdb's default. -fn set_family_if_available( - db: &mut fontdb::Database, - generic: GenericFamily, - candidates: &[&str], -) { +fn set_family_if_available(db: &mut fontdb::Database, generic: GenericFamily, candidates: &[&str]) { for &name in candidates { if has_font_family(db, name) { match generic { @@ -183,9 +179,7 @@ fn strip_tags(s: &str) -> String { .split_whitespace() .next() .unwrap_or(""); - let tag_name = tag_name_raw - .strip_suffix('/') - .unwrap_or(tag_name_raw); + let tag_name = tag_name_raw.strip_suffix('/').unwrap_or(tag_name_raw); let is_closing = tag.starts_with('/'); match tag_name { //
/
— always a newline (void element, never has a closing tag) @@ -670,11 +664,10 @@ mod tests { #[test] fn oversized_svg_is_downscaled() { - let svg = format!( - "\ + let svg = "\ \ " - ); + .to_string(); let png = render_svg_to_png( svg.as_bytes(), Path::new("/tmp/test.svg"), @@ -759,7 +752,7 @@ mod tests { if !outside .canonicalize() .unwrap() - .starts_with(&cwd.canonicalize().unwrap()) + .starts_with(cwd.canonicalize().unwrap()) { assert!(!is_path_allowed(&outside, SvgResources::Tree)); } diff --git a/src/terminal.rs b/src/terminal.rs index 27c4b37..105ae05 100644 --- a/src/terminal.rs +++ b/src/terminal.rs @@ -235,7 +235,11 @@ fn extract_version_parens(name: &str) -> Option { fn extract_version_space(name: &str) -> Option { let pos = name.find(' ')?; let ver = name[pos + 1..].trim(); - if ver.is_empty() { None } else { Some(ver.to_string()) } + if ver.is_empty() { + None + } else { + Some(ver.to_string()) + } } /// Find the String Terminator (ST) starting from `from`. @@ -295,7 +299,12 @@ trait TerminalQuerier { /// Identify what's at the current layer: send XTVERSION, fall back to DA2. /// Returns (terminal, optional mux detected at this layer). -fn identify_layer(q: &mut impl TerminalQuerier, query_bytes: &[u8], da2_bytes: &[u8], timeout: Duration) -> Option<(Terminal, Option)> { +fn identify_layer( + q: &mut impl TerminalQuerier, + query_bytes: &[u8], + da2_bytes: &[u8], + timeout: Duration, +) -> Option<(Terminal, Option)> { // Try XTVERSION if let Some(resp) = q.query(query_bytes, timeout) { if let Some(result) = parse_xtversion(&resp) { @@ -385,7 +394,10 @@ fn probe_outer(q: &mut impl TerminalQuerier, stack: &mut Vec, timeout: Dura pub fn detect_from_env() -> TerminalInfo { let mux_stack = detect_mux_env(); let terminal = detect_terminal_env(); - TerminalInfo { mux_stack, terminal } + TerminalInfo { + mux_stack, + terminal, + } } fn detect_mux_env() -> Vec { @@ -510,8 +522,7 @@ mod tty { if !poll_fd(self.read_fd, Duration::ZERO).unwrap_or(false) { break; } - let ret = - unsafe { libc::read(self.read_fd, byte.as_mut_ptr().cast(), 1) }; + let ret = unsafe { libc::read(self.read_fd, byte.as_mut_ptr().cast(), 1) }; if ret <= 0 { break; } @@ -532,8 +543,7 @@ mod tty { break; } let mut byte = [0u8]; - let ret = - unsafe { libc::read(self.read_fd, byte.as_mut_ptr().cast(), 1) }; + let ret = unsafe { libc::read(self.read_fd, byte.as_mut_ptr().cast(), 1) }; if ret <= 0 { break; } @@ -550,9 +560,7 @@ mod tty { impl TerminalQuerier for QuerySession { fn query(&mut self, request: &[u8], timeout: Duration) -> Option> { self.drain(); - let ret = unsafe { - libc::write(self.write_fd, request.as_ptr().cast(), request.len()) - }; + let ret = unsafe { libc::write(self.write_fd, request.as_ptr().cast(), request.len()) }; if ret < 0 { return None; } @@ -941,10 +949,7 @@ mod tests { // wraps through full stack and gets kitty. let xt_through_tmux = wrap_for_stack(XTVERSION, &[Mux::Tmux(None)]); let mut q = MockQuerier::new(vec![ - ( - XTVERSION.to_vec(), - Some(b"\x1bP>|tmux 3.3a\x1b\\".to_vec()), - ), + (XTVERSION.to_vec(), Some(b"\x1bP>|tmux 3.3a\x1b\\".to_vec())), // probe_outer: XTVERSION through 1 tmux -> kitty (terminal, not mux) ( xt_through_tmux.clone(), @@ -968,25 +973,13 @@ mod tests { let xt_2 = wrap_for_stack(XTVERSION, &[Mux::Tmux(None), Mux::Tmux(None)]); let mut q = MockQuerier::new(vec![ // Layer 0: XTVERSION -> tmux - ( - XTVERSION.to_vec(), - Some(b"\x1bP>|tmux 3.4\x1b\\".to_vec()), - ), + (XTVERSION.to_vec(), Some(b"\x1bP>|tmux 3.4\x1b\\".to_vec())), // probe_outer through 1 tmux -> another tmux - ( - xt_1.clone(), - Some(b"\x1bP>|tmux 3.3a\x1b\\".to_vec()), - ), + (xt_1.clone(), Some(b"\x1bP>|tmux 3.3a\x1b\\".to_vec())), // probe_outer through 2 tmux -> kitty (terminal) - ( - xt_2.clone(), - Some(b"\x1bP>|kitty(0.35.0)\x1b\\".to_vec()), - ), + (xt_2.clone(), Some(b"\x1bP>|kitty(0.35.0)\x1b\\".to_vec())), // detect_inband final query through full stack -> kitty - ( - xt_2, - Some(b"\x1bP>|kitty(0.35.0)\x1b\\".to_vec()), - ), + (xt_2, Some(b"\x1bP>|kitty(0.35.0)\x1b\\".to_vec())), ]); let info = detect_inband(&mut q); assert_eq!(info.mux_stack.len(), 2); @@ -1003,26 +996,17 @@ mod tests { let mut q = MockQuerier::new(vec![ // XTVERSION -> tmux (innermost) - ( - XTVERSION.to_vec(), - Some(b"\x1bP>|tmux 3.4\x1b\\".to_vec()), - ), + (XTVERSION.to_vec(), Some(b"\x1bP>|tmux 3.4\x1b\\".to_vec())), // Through tmux: XTVERSION times out, DA2 -> screen (xt_tmux.clone(), None), - ( - da_tmux.clone(), - Some(b"\x1b[>83;40801;0c".to_vec()), - ), + (da_tmux.clone(), Some(b"\x1b[>83;40801;0c".to_vec())), // Through tmux+screen: XTVERSION -> Ghostty ( xt_both.clone(), Some(b"\x1bP>|Ghostty(1.0.0)\x1b\\".to_vec()), ), // Final query through stack -> Ghostty - ( - xt_both, - Some(b"\x1bP>|Ghostty(1.0.0)\x1b\\".to_vec()), - ), + (xt_both, Some(b"\x1bP>|Ghostty(1.0.0)\x1b\\".to_vec())), ]); let info = detect_inband(&mut q); assert_eq!(info.mux_stack.len(), 2); @@ -1044,10 +1028,7 @@ mod tests { Some(b"\x1bP>|kitty(0.30.0)\x1b\\".to_vec()), ), // Final query - ( - xt_screen, - Some(b"\x1bP>|kitty(0.30.0)\x1b\\".to_vec()), - ), + (xt_screen, Some(b"\x1bP>|kitty(0.30.0)\x1b\\".to_vec())), ]); let info = detect_inband(&mut q); assert_eq!(info.mux_stack.len(), 1); @@ -1068,10 +1049,7 @@ mod tests { #[test] fn detect_both_timeout_returns_unknown() { - let mut q = MockQuerier::new(vec![ - (XTVERSION.to_vec(), None), - (DA2.to_vec(), None), - ]); + let mut q = MockQuerier::new(vec![(XTVERSION.to_vec(), None), (DA2.to_vec(), None)]); let info = detect_inband(&mut q); assert_eq!(info.terminal, Terminal::Unknown); assert!(info.mux_stack.is_empty()); @@ -1082,10 +1060,7 @@ mod tests { let xt_tmux = wrap_for_stack(XTVERSION, &[Mux::Tmux(None)]); let da_tmux = wrap_for_stack(DA2, &[Mux::Tmux(None)]); let mut q = MockQuerier::new(vec![ - ( - XTVERSION.to_vec(), - Some(b"\x1bP>|tmux 3.4\x1b\\".to_vec()), - ), + (XTVERSION.to_vec(), Some(b"\x1bP>|tmux 3.4\x1b\\".to_vec())), // probe_outer and final query all time out (xt_tmux, None), (da_tmux, None),