use std::io::Write;
use std::path::Path;
pub fn normalize_text(text: &str) -> String {
let mut lines: Vec<String> = text.lines().map(|l| l.trim_end().to_string()).collect();
while lines.last().is_some_and(|l| l.is_empty()) {
lines.pop();
}
lines.join("\n")
}
pub fn render_svg(text: &str, output_path: &Path, cols: u16, rows: u16) -> std::io::Result<()> {
let line_height: u32 = 20;
let char_width: u32 = 9;
let padding: u32 = 18;
let width = std::cmp::max(320, cols as u32 * char_width + padding * 2);
let height = std::cmp::max(160, rows as u32 * line_height + padding * 2);
let visible: Vec<&str> = if text.is_empty() {
vec![""]
} else {
text.lines().take(rows as usize).collect()
};
if let Some(parent) = output_path.parent() {
std::fs::create_dir_all(parent)?;
}
let mut parts = Vec::new();
parts.push(format!(
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width}\" height=\"{height}\" viewBox=\"0 0 {width} {height}\">"
));
parts.push("<rect width=\"100%\" height=\"100%\" fill=\"#101418\"/>".to_string());
parts.push(
"<style>text{font:14px ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;fill:#e6edf3;white-space:pre}</style>"
.to_string(),
);
for (index, line) in visible.iter().enumerate() {
let y = padding + line_height * (index as u32 + 1);
let escaped = html_escape(line);
parts.push(format!("<text x=\"{padding}\" y=\"{y}\">{escaped}</text>"));
}
parts.push("</svg>".to_string());
let content = parts.join("\n") + "\n";
atomic_write(output_path, content.as_bytes())
}
fn html_escape(s: &str) -> String {
s.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
.replace('\'', "'")
}
pub fn render_png(text: &str, output_path: &Path, cols: u16, rows: u16) -> std::io::Result<()> {
let line_height: u32 = 18;
let char_width: u32 = 9;
let padding: u32 = 18;
let width = std::cmp::max(320, cols as u32 * char_width + padding * 2);
let height = std::cmp::max(160, rows as u32 * line_height + padding * 2);
if let Some(parent) = output_path.parent() {
std::fs::create_dir_all(parent)?;
}
let mut img = image::RgbImage::new(width, height);
for pixel in img.pixels_mut() {
*pixel = image::Rgb([0x10, 0x14, 0x18]);
}
let visible: Vec<&str> = if text.is_empty() {
vec![""]
} else {
text.lines().take(rows as usize).collect()
};
for (row_idx, line) in visible.iter().enumerate() {
let y_base = padding + line_height * row_idx as u32;
for (col_idx, ch) in line.chars().take(cols as usize).enumerate() {
if ch == ' ' {
continue;
}
let x = padding + char_width * col_idx as u32;
for dy in 0..10 {
for dx in 0..6 {
let px = x + dx;
let py = y_base + dy;
if px < width && py < height {
img.put_pixel(px, py, image::Rgb([0xe6, 0xed, 0xf3]));
}
}
}
}
}
let dir = output_path.parent().unwrap_or_else(|| Path::new("."));
let mut tmp = tempfile::NamedTempFile::new_in(dir).map_err(std::io::Error::other)?;
img.write_to(&mut tmp, image::ImageFormat::Png)
.map_err(std::io::Error::other)?;
tmp.flush()?;
match tmp.persist(output_path) {
Ok(_) => Ok(()),
Err(e) => {
let _ = std::fs::remove_file(output_path);
e.file
.persist(output_path)
.map(|_| ())
.map_err(|e2| std::io::Error::other(e2.error))
}
}
}
fn atomic_write(dest: &Path, content: &[u8]) -> std::io::Result<()> {
if let Some(parent) = dest.parent() {
std::fs::create_dir_all(parent)?;
}
let dir = dest.parent().unwrap_or_else(|| Path::new("."));
let mut tmp = tempfile::NamedTempFile::new_in(dir)?;
tmp.write_all(content)?;
tmp.flush()?;
match tmp.persist(dest) {
Ok(_) => Ok(()),
Err(e) => {
let _ = std::fs::remove_file(dest);
e.file.persist(dest).map(|_| ()).map_err(|e2| e2.error)
}
}
}
pub fn render_by_extension(text: &str, path: &Path, cols: u16, rows: u16) -> std::io::Result<()> {
match path
.extension()
.and_then(|e| e.to_str())
.unwrap_or("svg")
.to_ascii_lowercase()
.as_str()
{
"png" => render_png(text, path, cols, rows),
_ => render_svg(text, path, cols, rows),
}
}