use crate::capture::{
CapturedScreen, DEFAULT_MAX_SCROLLBACK_LINES, LineSelection, cell_has_content,
effective_scrollback_lines,
};
use crate::config::{ChromeConfig, ThemeConfig};
use crate::redaction::{ManualRedactions, RedactionEngine, RedactionMap};
use crate::shaping::{FontSource, GlyphBitmap, RunCell, RunRequest, ShapingEngine, ShapingOptions};
use crate::unicode;
use anyhow::{Context, Result};
use chrono::Utc;
use fontdue::{Font, FontSettings};
use image::{ImageBuffer, Rgba, RgbaImage};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use unicode_script::UnicodeScript;
const EMBEDDED_FONT: &[u8] = include_bytes!("../fonts/JetBrainsMono-Regular.ttf");
#[cfg(test)]
const REDACT_BG: Rgba<u8> = Rgba([212, 25, 25, 255]);
const RENDER_SCALE: u32 = 2;
const MIN_CONTENT_COLS: u32 = 1;
const MIN_CONTENT_ROWS: u32 = 1;
const TIMESTAMP_FONT_SCALE: f32 = 0.65;
const TIMESTAMP_GAP: u32 = 4;
const MAX_IMAGE_PIXELS: u64 = 64_000_000;
const MAX_RENDER_BYTES: u64 = 320 * 1024 * 1024;
const BYTES_PER_PIXEL: u64 = 4;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RenderMeta {
pub cols: u16,
pub rows: u16,
pub theme: Option<String>,
pub chrome: Option<ChromeOptions>,
#[serde(default = "default_auto_crop")]
pub auto_crop: bool,
#[serde(default)]
pub from_screen: bool,
}
impl Default for RenderMeta {
fn default() -> Self {
Self {
cols: 80,
rows: 24,
theme: None,
chrome: None,
auto_crop: default_auto_crop(),
from_screen: false,
}
}
}
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
pub struct RenderContext {
#[serde(flatten)]
pub meta: RenderMeta,
#[serde(default)]
pub lines: LineSelection,
#[serde(default)]
pub truncated: bool,
}
impl RenderContext {
pub fn from_meta(meta: RenderMeta) -> Self {
Self {
meta,
lines: LineSelection::All,
truncated: false,
}
}
}
impl std::ops::Deref for RenderContext {
type Target = RenderMeta;
fn deref(&self) -> &RenderMeta {
&self.meta
}
}
fn default_auto_crop() -> bool {
true
}
pub type RenderOutput = (PathBuf, String, Vec<(String, usize)>, RenderMeta);
pub type RenderOutputWithContext = (PathBuf, String, Vec<(String, usize)>, RenderContext);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComposeLayout {
Horizontal,
Vertical,
}
impl ComposeLayout {
pub fn parse(s: &str) -> Result<Self> {
match s.trim().to_ascii_lowercase().as_str() {
"horizontal" | "h" | "row" | "side-by-side" => Ok(Self::Horizontal),
"vertical" | "v" | "column" | "stacked" => Ok(Self::Vertical),
other => anyhow::bail!(
"unknown compose layout '{}': use 'horizontal' or 'vertical'",
other
),
}
}
}
const TRAFFIC_LIGHT_RADIUS: u32 = 5;
const TRAFFIC_LIGHT_FIRST_CENTER: u32 = 18;
const TRAFFIC_LIGHT_PITCH: u32 = 16;
const DIVIDER_COLOR_DARK: Rgba<u8> = Rgba([0x6e, 0x76, 0x80, 255]);
const DIVIDER_COLOR_LIGHT: Rgba<u8> = Rgba([0x9a, 0x9a, 0x9a, 255]);
fn divider_color_for(background: Rgba<u8>) -> Rgba<u8> {
let [r, g, b, _] = background.0;
let luminance = 0.299 * r as f32 + 0.587 * g as f32 + 0.114 * b as f32;
if luminance < 128.0 {
DIVIDER_COLOR_DARK
} else {
DIVIDER_COLOR_LIGHT
}
}
fn sample_background(img: &RgbaImage, fallback: Rgba<u8>) -> Rgba<u8> {
let (w, h) = img.dimensions();
if w == 0 || h == 0 {
return fallback;
}
let candidates = [
(w / 2, 2.min(h - 1)),
(4.min(w - 1), 4.min(h - 1)),
(2.min(w - 1), h / 2),
(0, 0),
];
for (x, y) in candidates {
let p = *img.get_pixel(x, y);
if p[3] == 255 {
return Rgba([p[0], p[1], p[2], 255]);
}
}
fallback
}
fn normalize_newlines(data: &[u8]) -> std::borrow::Cow<'_, [u8]> {
let has_bare_lf = data
.iter()
.enumerate()
.any(|(i, &b)| b == b'\n' && (i == 0 || data[i - 1] != b'\r'));
if !has_bare_lf {
return std::borrow::Cow::Borrowed(data);
}
let mut out = Vec::with_capacity(data.len() + 16);
let mut prev = 0u8;
for &b in data {
if b == b'\n' && prev != b'\r' {
out.push(b'\r');
}
out.push(b);
prev = b;
}
std::borrow::Cow::Owned(out)
}
pub fn compose_images(
paths: &[PathBuf],
layout: ComposeLayout,
divider: u32,
background: Rgba<u8>,
) -> Result<RgbaImage> {
if paths.len() < 2 {
anyhow::bail!("compose requires at least two images (got {})", paths.len());
}
let mut sources: Vec<RgbaImage> = Vec::with_capacity(paths.len());
for p in paths {
let img = image::open(p)
.with_context(|| format!("Failed to open image {:?}", p))?
.to_rgba8();
sources.push(img);
}
let canvas_bg = sample_background(&sources[0], background);
let (target_w, target_h) = match layout {
ComposeLayout::Horizontal => (0, sources.iter().map(|i| i.height()).max().unwrap_or(1)),
ComposeLayout::Vertical => (sources.iter().map(|i| i.width()).max().unwrap_or(1), 0),
};
let panes: Vec<RgbaImage> = sources
.into_iter()
.map(|img| {
let w = target_w.max(img.width()).max(1);
let h = target_h.max(img.height()).max(1);
if (w, h) == img.dimensions() {
return img;
}
let pane_bg = sample_background(&img, canvas_bg);
let mut padded: RgbaImage = ImageBuffer::from_pixel(w, h, pane_bg);
image::imageops::overlay(&mut padded, &img, 0, 0);
padded
})
.collect();
let total_divider = divider * (panes.len() as u32 - 1);
let (width, height) = match layout {
ComposeLayout::Horizontal => (
panes.iter().map(|i| i.width()).sum::<u32>() + total_divider,
panes.iter().map(|i| i.height()).max().unwrap_or(0),
),
ComposeLayout::Vertical => (
panes.iter().map(|i| i.width()).max().unwrap_or(0),
panes.iter().map(|i| i.height()).sum::<u32>() + total_divider,
),
};
let divider_color = divider_color_for(canvas_bg);
let mut canvas: RgbaImage = ImageBuffer::from_pixel(width.max(1), height.max(1), canvas_bg);
let mut offset = 0u32;
for (idx, src) in panes.iter().enumerate() {
match layout {
ComposeLayout::Horizontal => {
image::imageops::overlay(&mut canvas, src, offset as i64, 0);
offset += src.width();
if idx + 1 < panes.len() && divider > 0 {
fill_rect(&mut canvas, offset, 0, divider, height, divider_color);
offset += divider;
}
}
ComposeLayout::Vertical => {
image::imageops::overlay(&mut canvas, src, 0, offset as i64);
offset += src.height();
if idx + 1 < panes.len() && divider > 0 {
fill_rect(&mut canvas, 0, offset, width, divider, divider_color);
offset += divider;
}
}
}
}
Ok(canvas)
}
fn fill_rect(canvas: &mut RgbaImage, x: u32, y: u32, w: u32, h: u32, color: Rgba<u8>) {
let (cw, ch) = canvas.dimensions();
let x_end = (x + w).min(cw);
let y_end = (y + h).min(ch);
for py in y..y_end {
for px in x..x_end {
canvas.put_pixel(px, py, color);
}
}
}
pub struct RedactionRequest<'a> {
pub engine: &'a RedactionEngine,
pub rules: Option<Vec<String>>,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct TextOptions {
pub strip_ansi: bool,
pub redact_text: bool,
pub embed_description: bool,
pub from_screen: bool,
}
const MAX_TITLE_CHARS: usize = 60;
#[derive(Debug, Clone)]
pub struct Theme {
pub foreground: Rgba<u8>,
pub background: Rgba<u8>,
pub palette: [Rgba<u8>; 16],
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ChromeOptions {
pub enabled: bool,
pub preset: String,
pub title: Option<String>,
pub timestamp: bool,
pub shadow: bool,
pub radius: u32,
#[serde(default = "default_true")]
pub rounded: bool,
pub outer_padding: u32,
pub title_bar_height: u32,
}
fn default_true() -> bool {
true
}
impl ChromeOptions {
pub fn from_config(config: &ChromeConfig) -> Self {
Self {
enabled: config.enabled && config.preset != "none",
preset: config.preset.clone(),
title: config.title.clone(),
timestamp: config.timestamp,
shadow: config.shadow,
radius: config.radius,
rounded: config.rounded,
outer_padding: config.outer_padding,
title_bar_height: config.title_bar_height,
}
}
}
impl Theme {
pub fn from_config(config: &ThemeConfig) -> Result<Self> {
Ok(Self {
foreground: parse_hex_color(&config.foreground)?,
background: parse_hex_color(&config.background)?,
palette: {
let mut arr = [Rgba([0, 0, 0, 255]); 16];
for (i, hex) in config.palette.iter().enumerate() {
arr[i] = parse_hex_color(hex)?;
}
arr
},
})
}
pub fn dark() -> Self {
Self {
foreground: Rgba([204, 204, 204, 255]),
background: Rgba([30, 30, 30, 255]),
palette: [
Rgba([30, 30, 30, 255]),
Rgba([204, 0, 0, 255]),
Rgba([78, 154, 6, 255]),
Rgba([196, 160, 0, 255]),
Rgba([52, 101, 164, 255]),
Rgba([117, 80, 123, 255]),
Rgba([6, 152, 160, 255]),
Rgba([211, 215, 207, 255]),
Rgba([85, 87, 83, 255]),
Rgba([239, 41, 41, 255]),
Rgba([138, 226, 52, 255]),
Rgba([252, 233, 79, 255]),
Rgba([114, 159, 207, 255]),
Rgba([173, 127, 168, 255]),
Rgba([52, 226, 226, 255]),
Rgba([238, 238, 236, 255]),
],
}
}
}
fn parse_hex_color(hex: &str) -> Result<Rgba<u8>> {
let hex = hex.trim().trim_start_matches('#');
anyhow::ensure!(
hex.len() == 6 && hex.bytes().all(|b| b.is_ascii_hexdigit()),
"Invalid hex color: #{}",
hex
);
let r = u8::from_str_radix(&hex[0..2], 16)?;
let g = u8::from_str_radix(&hex[2..4], 16)?;
let b = u8::from_str_radix(&hex[4..6], 16)?;
Ok(Rgba([r, g, b, 255]))
}
fn font_ascent(font: &Font, size: f32) -> f32 {
font.horizontal_line_metrics(size)
.map(|m| m.ascent)
.unwrap_or(size * 0.8)
}
fn font_line_height(font: &Font, size: f32) -> f32 {
font.horizontal_line_metrics(size)
.map(|m| m.new_line_size)
.unwrap_or(size * 1.2)
}
fn font_covers(font: &Font, ch: char, size: f32) -> bool {
if !font.has_glyph(ch) {
return false;
}
if ch.is_whitespace() {
return true;
}
let metrics = font.metrics(ch, size);
metrics.width > 0 && metrics.height > 0
}
struct ChosenFont<'a> {
font: &'a Font,
is_fallback: bool,
}
#[derive(Clone, Copy, Default)]
struct GlyphPlacement {
ascent: Option<f32>,
center_width: Option<u32>,
}
impl GlyphPlacement {
fn natural() -> Self {
Self::default()
}
fn fallback(ascent: f32, width: u32) -> Self {
Self {
ascent: Some(ascent),
center_width: Some(width),
}
}
}
fn fallback_font_size(font: &Font, ch: char, font_size: f32, target_advance: u32) -> f32 {
let advance = font.metrics(ch, font_size).advance_width;
if advance <= 0.0 || target_advance == 0 {
return font_size;
}
let ratio = (target_advance as f32 / advance).clamp(0.5, 1.5);
font_size * ratio
}
pub fn save_png(img: &RgbaImage, path: &Path, description: Option<&str>) -> Result<()> {
let file = std::fs::File::create(path)
.with_context(|| format!("Failed to create image file {:?}", path))?;
let writer = std::io::BufWriter::new(file);
let mut encoder = png::Encoder::new(writer, img.width(), img.height());
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
if let Some(text) = description {
let text = description_text_chunk(text);
if !text.is_empty() {
encoder
.add_itxt_chunk("Description".to_string(), text)
.with_context(|| format!("Failed to embed description in {:?}", path))?;
}
}
let mut writer = encoder
.write_header()
.with_context(|| format!("Failed to write PNG header for {:?}", path))?;
writer
.write_image_data(img.as_raw())
.with_context(|| format!("Failed to write PNG data for {:?}", path))?;
writer
.finish()
.with_context(|| format!("Failed to finalize PNG {:?}", path))?;
Ok(())
}
const MAX_DESCRIPTION_BYTES: usize = 256 * 1024;
pub fn read_png_description(path: &Path) -> Option<String> {
let file = std::fs::File::open(path)
.map_err(|e| tracing::debug!("No description read from {:?}: {}", path, e))
.ok()?;
let decoder = png::Decoder::new(std::io::BufReader::new(file));
let reader = decoder
.read_info()
.map_err(|e| tracing::debug!("No description read from {:?}: {}", path, e))
.ok()?;
let info = reader.info();
let chunk = info
.utf8_text
.iter()
.find(|c| c.keyword.eq_ignore_ascii_case("Description"))?;
let text = chunk
.get_text()
.map_err(|e| tracing::debug!("Undecodable description in {:?}: {}", path, e))
.ok()?;
let text = text.trim_end_matches('\n').to_string();
if text.is_empty() { None } else { Some(text) }
}
fn composed_description(paths: &[PathBuf]) -> Option<String> {
let descriptions: Vec<Option<String>> = paths
.iter()
.map(|p| read_png_description(p))
.collect::<Vec<_>>();
if descriptions.iter().all(Option::is_none) {
return None;
}
let mut out = String::new();
for (idx, description) in descriptions.iter().enumerate() {
if idx > 0 {
out.push_str(&format!("\n\n--- Pane {} ---\n\n", idx + 1));
}
match description {
Some(text) => out.push_str(text),
None => out.push_str("(no description)"),
}
}
Some(out)
}
fn screen_ansi_text(screen: &CapturedScreen, cols: u16) -> String {
let (rows, _) = screen.size();
let mut out = String::new();
for row in 0..rows {
if row > 0 {
out.push('\n');
}
let mut style: Option<CellStyle> = None;
let last_col = (0..cols)
.rev()
.find(|&col| {
screen
.cell(row, col)
.map(|c| c.has_contents())
.unwrap_or(false)
})
.map(|col| col + 1)
.unwrap_or(0);
for col in 0..last_col {
let Some(cell) = screen.cell(row, col) else {
continue;
};
if cell.is_wide_continuation() {
continue;
}
let cell_style = CellStyle::of(cell);
if style != Some(cell_style) {
out.push_str(&cell_style.sgr());
style = Some(cell_style);
}
let contents = cell.contents();
if contents.is_empty() {
out.push(' ');
} else {
out.push_str(contents);
}
}
if style.is_some() {
out.push_str("\x1b[0m");
}
}
out.trim_end().to_string()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct CellStyle {
fg: vt100::Color,
bg: vt100::Color,
bold: bool,
dim: bool,
italic: bool,
underline: bool,
inverse: bool,
}
impl CellStyle {
fn of(cell: &vt100::Cell) -> Self {
Self {
fg: cell.fgcolor(),
bg: cell.bgcolor(),
bold: cell.bold(),
dim: cell.dim(),
italic: cell.italic(),
underline: cell.underline(),
inverse: cell.inverse(),
}
}
fn sgr(&self) -> String {
let mut params: Vec<String> = vec!["0".to_string()];
for (on, code) in [
(self.bold, "1"),
(self.dim, "2"),
(self.italic, "3"),
(self.underline, "4"),
(self.inverse, "7"),
] {
if on {
params.push(code.to_string());
}
}
match self.fg {
vt100::Color::Default => {}
vt100::Color::Idx(i) if i < 8 => params.push(format!("{}", 30 + i)),
vt100::Color::Idx(i) if i < 16 => params.push(format!("{}", 90 + i - 8)),
vt100::Color::Idx(i) => params.push(format!("38;5;{}", i)),
vt100::Color::Rgb(r, g, b) => params.push(format!("38;2;{};{};{}", r, g, b)),
}
match self.bg {
vt100::Color::Default => {}
vt100::Color::Idx(i) if i < 8 => params.push(format!("{}", 40 + i)),
vt100::Color::Idx(i) if i < 16 => params.push(format!("{}", 100 + i - 8)),
vt100::Color::Idx(i) => params.push(format!("48;5;{}", i)),
vt100::Color::Rgb(r, g, b) => params.push(format!("48;2;{};{};{}", r, g, b)),
}
format!("\x1b[{}m", params.join(";"))
}
}
fn description_text_chunk(text: &str) -> String {
let mut out = String::with_capacity(text.len().min(MAX_DESCRIPTION_BYTES));
for ch in text.chars() {
if ch != '\n' && ((ch as u32) < 0x20 || (ch as u32) == 0x7f) {
continue;
}
if out.len() + ch.len_utf8() > MAX_DESCRIPTION_BYTES {
break;
}
out.push(ch);
}
while out.ends_with('\n') {
out.pop();
}
out
}
pub struct ThemeFonts {
font: Font,
font_bold: Option<Font>,
fallback_fonts: Vec<Font>,
cell_width: u32,
cell_height: u32,
shaping: ShapingEngine,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct FontChainSpec {
primary: Option<PathBuf>,
bold: Option<PathBuf>,
fallbacks: Vec<PathBuf>,
}
impl FontChainSpec {
fn shaping_sources(&self) -> Vec<FontSource> {
let mut sources = Vec::with_capacity(self.fallbacks.len() + 3);
let push = |source: FontSource, sources: &mut Vec<FontSource>| {
if !sources.contains(&source) {
sources.push(source);
}
};
if let Some(primary) = &self.primary {
push(FontSource::File(primary.clone()), &mut sources);
}
if let Some(bold) = &self.bold {
push(FontSource::File(bold.clone()), &mut sources);
}
push(FontSource::Embedded(EMBEDDED_FONT), &mut sources);
for fallback in &self.fallbacks {
push(FontSource::File(fallback.clone()), &mut sources);
}
sources
}
}
impl ThemeFonts {
fn load(spec: &FontChainSpec, font_size: f32, shaping: &ShapingOptions) -> Result<Self> {
let font_data = match spec.primary.as_deref() {
Some(path) => {
std::fs::read(path).with_context(|| format!("Failed to read font: {:?}", path))?
}
None => EMBEDDED_FONT.to_vec(),
};
let font = Font::from_bytes(font_data, FontSettings::default())
.map_err(|e| anyhow::anyhow!("Failed to parse font: {}", e))?;
let font_bold = if let Some(path) = spec.bold.as_deref() {
let data = std::fs::read(path)
.with_context(|| format!("Failed to read bold font: {:?}", path))?;
Some(
Font::from_bytes(data, FontSettings::default())
.map_err(|e| anyhow::anyhow!("Failed to parse bold font: {}", e))?,
)
} else {
None
};
let mut fallback_fonts = Vec::with_capacity(spec.fallbacks.len() + 1);
match Font::from_bytes(EMBEDDED_FONT, FontSettings::default()) {
Ok(embedded) => fallback_fonts.push(embedded),
Err(e) => tracing::warn!("Failed to parse embedded fallback font: {}", e),
}
for path in &spec.fallbacks {
match std::fs::read(path) {
Ok(data) => match Font::from_bytes(data, FontSettings::default()) {
Ok(parsed) => fallback_fonts.push(parsed),
Err(e) => tracing::warn!("Ignoring unusable fallback font {:?}: {}", path, e),
},
Err(e) => tracing::warn!("Ignoring unreadable fallback font {:?}: {}", path, e),
}
}
let metrics = font.metrics('M', font_size);
let cell_width = metrics.advance_width.ceil() as u32;
let cell_height = font_line_height(&font, font_size).ceil() as u32;
Ok(Self {
font,
font_bold,
fallback_fonts,
cell_width,
cell_height,
shaping: ShapingEngine::new(spec.shaping_sources(), shaping.clone()),
})
}
fn chain_covers(&self, ch: char, bold: bool, font_size: f32) -> bool {
let primary = match (bold, self.font_bold.as_ref()) {
(true, Some(bold_font)) => bold_font,
_ => &self.font,
};
font_covers(primary, ch, font_size)
|| self
.fallback_fonts
.iter()
.any(|font| font_covers(font, ch, font_size))
}
#[cfg(test)]
pub(crate) fn shaping(&self) -> &ShapingEngine {
&self.shaping
}
}
#[derive(Debug, Clone, Default)]
pub struct FontSelection {
pub font_override: Option<PathBuf>,
pub font_bold_override: Option<PathBuf>,
pub global_font: Option<PathBuf>,
pub global_fallback_fonts: Vec<PathBuf>,
}
impl FontSelection {
fn spec_for(&self, theme: Option<&ThemeConfig>) -> FontChainSpec {
let (theme_font, theme_bold) = match theme {
Some(t) => t.resolved_font_paths(),
None => (None, None),
};
let mut fallbacks = match theme {
Some(t) => t.resolved_fallback_font_paths(),
None => Vec::new(),
};
fallbacks.extend(self.global_fallback_fonts.iter().cloned());
FontChainSpec {
primary: self
.font_override
.clone()
.or(theme_font)
.or_else(|| self.global_font.clone()),
bold: self.font_bold_override.clone().or(theme_bold),
fallbacks,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RendererOptions {
pub max_scrollback_lines: usize,
}
impl Default for RendererOptions {
fn default() -> Self {
Self {
max_scrollback_lines: DEFAULT_MAX_SCROLLBACK_LINES,
}
}
}
impl RendererOptions {
pub fn with_max_scrollback_lines(mut self, lines: usize) -> Self {
self.max_scrollback_lines = lines;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct RenderOptions {
pub lines: LineSelection,
}
impl RenderOptions {
pub fn with_lines(mut self, selection: LineSelection) -> Self {
self.lines = selection;
self
}
pub fn with_manual(self, manual: &ManualRedactions) -> ExtendedRenderOptions<'_> {
ExtendedRenderOptions::from(self).with_manual(manual)
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct ExtendedRenderOptions<'a> {
pub base: RenderOptions,
pub manual: Option<&'a ManualRedactions>,
}
impl From<RenderOptions> for ExtendedRenderOptions<'_> {
fn from(base: RenderOptions) -> Self {
Self { base, manual: None }
}
}
impl PartialEq for ExtendedRenderOptions<'_> {
fn eq(&self, other: &Self) -> bool {
self.base == other.base
&& match (self.manual, other.manual) {
(None, None) => true,
(Some(a), Some(b)) => std::ptr::eq(a, b),
_ => false,
}
}
}
impl Eq for ExtendedRenderOptions<'_> {}
impl<'a> ExtendedRenderOptions<'a> {
pub fn with_lines(mut self, selection: LineSelection) -> Self {
self.base.lines = selection;
self
}
pub fn with_manual(mut self, manual: &'a ManualRedactions) -> Self {
self.manual = Some(manual);
self
}
pub fn with_optional_manual(mut self, manual: Option<&'a ManualRedactions>) -> Self {
self.manual = manual;
self
}
pub fn lines(&self) -> LineSelection {
self.base.lines
}
}
pub struct Renderer {
theme_fonts: HashMap<String, Arc<ThemeFonts>>,
default_fonts: Arc<ThemeFonts>,
font_size: f32,
themes: HashMap<String, Theme>,
default_theme: String,
default_chrome: ChromeOptions,
padding: u32,
max_scrollback_lines: usize,
}
impl Renderer {
pub fn new(
fonts: &FontSelection,
font_size: f32,
theme_configs: &HashMap<String, ThemeConfig>,
default_theme: &str,
chrome_config: &ChromeConfig,
) -> Result<Self> {
Self::new_with_options(
fonts,
font_size,
theme_configs,
default_theme,
chrome_config,
RendererOptions::default(),
)
}
pub fn new_with_options(
fonts: &FontSelection,
font_size: f32,
theme_configs: &HashMap<String, ThemeConfig>,
default_theme: &str,
chrome_config: &ChromeConfig,
options: RendererOptions,
) -> Result<Self> {
Self::new_with_shaping(
fonts,
font_size,
theme_configs,
default_theme,
chrome_config,
options,
ShapingOptions::from_env(),
)
}
#[allow(clippy::too_many_arguments)]
pub fn new_with_shaping(
fonts: &FontSelection,
font_size: f32,
theme_configs: &HashMap<String, ThemeConfig>,
default_theme: &str,
chrome_config: &ChromeConfig,
options: RendererOptions,
shaping: ShapingOptions,
) -> Result<Self> {
let mut themes = HashMap::new();
for (name, config) in theme_configs {
match Theme::from_config(config) {
Ok(theme) => {
themes.insert(name.clone(), theme);
}
Err(e) => {
tracing::warn!("Failed to parse theme '{}': {}", name, e);
}
}
}
themes.entry("dark".to_string()).or_insert_with(Theme::dark);
let default_spec = fonts.spec_for(theme_configs.get(default_theme));
let default_fonts = Arc::new(ThemeFonts::load(&default_spec, font_size, &shaping)?);
let mut by_spec: HashMap<FontChainSpec, Arc<ThemeFonts>> = HashMap::new();
by_spec.insert(default_spec, Arc::clone(&default_fonts));
let mut theme_fonts: HashMap<String, Arc<ThemeFonts>> = HashMap::new();
for name in themes.keys() {
let spec = fonts.spec_for(theme_configs.get(name));
if let Some(existing) = by_spec.get(&spec) {
theme_fonts.insert(name.clone(), Arc::clone(existing));
continue;
}
match ThemeFonts::load(&spec, font_size, &shaping) {
Ok(loaded) => {
let loaded = Arc::new(loaded);
by_spec.insert(spec, Arc::clone(&loaded));
theme_fonts.insert(name.clone(), loaded);
}
Err(e) => {
tracing::warn!(
"Failed to load fonts for theme '{}': {}; using the default fonts",
name,
e
);
theme_fonts.insert(name.clone(), Arc::clone(&default_fonts));
}
}
}
Ok(Self {
theme_fonts,
default_fonts,
font_size,
themes,
default_theme: default_theme.to_string(),
default_chrome: ChromeOptions::from_config(chrome_config),
padding: 16,
max_scrollback_lines: options.max_scrollback_lines,
})
}
fn resolve_theme_name<'a>(&'a self, name: Option<&'a str>) -> &'a str {
let name = name.unwrap_or(&self.default_theme);
if self.themes.contains_key(name) {
name
} else if self.themes.contains_key(&self.default_theme) {
&self.default_theme
} else {
"dark"
}
}
pub fn get_theme(&self, name: Option<&str>) -> &Theme {
let name = self.resolve_theme_name(name);
self.themes
.get(name)
.or_else(|| self.themes.get(&self.default_theme))
.or_else(|| self.themes.get("dark"))
.expect("no themes available")
}
fn fonts_for(&self, name: Option<&str>) -> &ThemeFonts {
let name = self.resolve_theme_name(name);
self.theme_fonts
.get(name)
.map(Arc::as_ref)
.unwrap_or(&self.default_fonts)
}
pub fn theme_names(&self) -> Vec<String> {
let mut names: Vec<String> = self.themes.keys().cloned().collect();
names.sort();
names
}
#[allow(clippy::too_many_arguments)]
pub fn render_bytes(
&self,
data: &[u8],
cols: u16,
rows: u16,
output_dir: &Path,
output_name: Option<&str>,
theme_name: Option<&str>,
chrome: Option<&ChromeOptions>,
redaction: Option<&RedactionRequest>,
text: TextOptions,
auto_crop: bool,
) -> Result<RenderOutput> {
let (path, text, audit, context) = self.render_bytes_with_options(
data,
cols,
rows,
output_dir,
output_name,
theme_name,
chrome,
redaction,
text,
auto_crop,
RenderOptions::default(),
)?;
Ok((path, text, audit, context.meta))
}
#[allow(clippy::too_many_arguments)]
pub fn render_bytes_with_options(
&self,
data: &[u8],
cols: u16,
rows: u16,
output_dir: &Path,
output_name: Option<&str>,
theme_name: Option<&str>,
chrome: Option<&ChromeOptions>,
redaction: Option<&RedactionRequest>,
text: TextOptions,
auto_crop: bool,
options: RenderOptions,
) -> Result<RenderOutputWithContext> {
self.render_bytes_with_extended_options(
data,
cols,
rows,
output_dir,
output_name,
theme_name,
chrome,
redaction,
text,
auto_crop,
options.into(),
)
}
#[allow(clippy::too_many_arguments)]
pub fn render_bytes_with_extended_options(
&self,
data: &[u8],
cols: u16,
rows: u16,
output_dir: &Path,
output_name: Option<&str>,
theme_name: Option<&str>,
chrome: Option<&ChromeOptions>,
redaction: Option<&RedactionRequest>,
text: TextOptions,
auto_crop: bool,
options: ExtendedRenderOptions<'_>,
) -> Result<RenderOutputWithContext> {
let lines = options.base.lines;
let capture = self.capture(data, rows, cols, lines);
let screen = &capture;
if capture.truncated() {
tracing::warn!(
"capture truncated: more output scrolled off than the {}-line scrollback \
could hold, so the oldest lines were dropped; raise `max_scrollback_lines` \
(a wide terminal caps it below the configured value) or render one end with \
a head/tail selection",
self.effective_scrollback_lines(rows, cols)
);
}
let text = TextOptions {
from_screen: text.from_screen || !lines.is_all(),
..text
};
if let Some(req) = redaction {
tracing::debug!("redaction: {} active rule(s)", req.engine.rule_count());
}
let mut redaction_map =
redaction.map(|req| req.engine.redact_screen(screen, req.rules.as_deref()));
if let Some(manual) = options.manual.filter(|manual| !manual.is_empty()) {
let (rendered_rows, rendered_cols) =
self.rendered_bounds(screen, theme_name, auto_crop);
manual.validate_bounds(rendered_rows, rendered_cols)?;
manual.apply_to(
screen,
redaction_map.get_or_insert_with(RedactionMap::default),
);
}
if let Some(map) = &redaction_map
&& !map.is_empty()
{
tracing::info!(
"redaction: masked {} cell(s) ({})",
map.cell_count(),
map.audit_summary()
);
}
let plain_text = self.output_text(data, screen, cols, redaction_map.as_ref(), text);
let theme = self.get_theme(theme_name);
let fonts = self.fonts_for(theme_name);
let chrome = chrome.unwrap_or(&self.default_chrome);
let image = self.render_to_image(
screen,
theme,
fonts,
chrome,
redaction_map.as_ref(),
auto_crop,
)?;
let base = sanitize_base_name(output_name.unwrap_or(""));
let path = unique_png_path(output_dir, &base);
let description = self.description_text(screen, cols, redaction_map.as_ref(), text);
save_png(&image, &path, description.as_deref())?;
let context = RenderContext {
meta: RenderMeta {
cols,
rows,
theme: theme_name.map(str::to_owned),
chrome: Some(chrome.clone()),
auto_crop,
from_screen: text.from_screen,
},
lines,
truncated: capture.truncated(),
};
let audit = redaction_map.map(|m| m.counts).unwrap_or_default();
Ok((path, plain_text, audit, context))
}
pub fn capture(
&self,
data: &[u8],
rows: u16,
cols: u16,
lines: LineSelection,
) -> CapturedScreen {
let normalized = normalize_newlines(data);
CapturedScreen::parse_selected(&normalized, rows, cols, self.max_scrollback_lines, lines)
}
pub fn effective_scrollback_lines(&self, rows: u16, cols: u16) -> usize {
effective_scrollback_lines(rows, cols, self.max_scrollback_lines)
}
pub fn capture_for(&self, data: &[u8], context: &RenderContext) -> CapturedScreen {
self.capture(data, context.meta.rows, context.meta.cols, context.lines)
}
pub fn rendered_bounds(
&self,
screen: &CapturedScreen,
theme_name: Option<&str>,
auto_crop: bool,
) -> (u16, u16) {
let layout = self.screen_layout(screen, self.fonts_for(theme_name), auto_crop);
(
u16::try_from(layout.content_rows).unwrap_or(u16::MAX),
u16::try_from(layout.content_cols).unwrap_or(u16::MAX),
)
}
pub fn rendered_bounds_for(
&self,
screen: &CapturedScreen,
context: &RenderContext,
) -> (u16, u16) {
self.rendered_bounds(
screen,
context.meta.theme.as_deref(),
context.meta.auto_crop,
)
}
pub fn max_scrollback_lines(&self) -> usize {
self.max_scrollback_lines
}
pub fn render_redaction_to(
&self,
data: &[u8],
meta: &RenderMeta,
map: &RedactionMap,
out_path: &Path,
text: TextOptions,
) -> Result<(String, Vec<(String, usize)>)> {
self.render_redaction_to_with_context(
data,
&RenderContext::from_meta(meta.clone()),
map,
out_path,
text,
)
}
pub fn render_redaction_to_with_context(
&self,
data: &[u8],
context: &RenderContext,
map: &RedactionMap,
out_path: &Path,
text: TextOptions,
) -> Result<(String, Vec<(String, usize)>)> {
let meta = &context.meta;
let capture = self.capture_for(data, context);
let screen = &capture;
let plain_text = self.output_text(data, screen, meta.cols, Some(map), text);
let theme = self.get_theme(meta.theme.as_deref());
let chrome = meta
.chrome
.clone()
.unwrap_or_else(|| self.default_chrome.clone());
let fonts = self.fonts_for(meta.theme.as_deref());
let image =
self.render_to_image(screen, theme, fonts, &chrome, Some(map), meta.auto_crop)?;
let description = self.description_text(screen, meta.cols, Some(map), text);
save_png(&image, out_path, description.as_deref())?;
Ok((plain_text, map.counts.clone()))
}
#[allow(clippy::too_many_arguments)]
pub fn compose_screenshots(
&self,
paths: &[PathBuf],
layout: ComposeLayout,
divider: u32,
theme_name: Option<&str>,
chrome: Option<&ChromeOptions>,
output_dir: &Path,
output: Option<&Path>,
embed_description: bool,
) -> Result<PathBuf> {
let theme = self.get_theme(theme_name);
let fonts = self.fonts_for(theme_name);
let description = if embed_description {
composed_description(paths)
} else {
None
};
let composed = compose_images(paths, layout, divider, theme.background)?;
let composed = match chrome {
Some(chrome) if chrome.enabled => {
self.compose_with_chrome(composed, theme, fonts, chrome)
}
_ => {
let mut composed = composed;
if self.default_chrome.rounded {
self.round_image_corners(
&mut composed,
self.default_chrome.radius * RENDER_SCALE,
);
}
composed
}
};
let path = match output {
Some(p) => p.to_path_buf(),
None => {
let id = &uuid::Uuid::new_v4().to_string()[..8];
output_dir.join(format!("termshot_composed_{}.png", id))
}
};
save_png(&composed, &path, description.as_deref())
.with_context(|| format!("Failed to save composed image to {:?}", path))?;
Ok(path)
}
fn output_text(
&self,
data: &[u8],
screen: &CapturedScreen,
cols: u16,
redaction: Option<&RedactionMap>,
opts: TextOptions,
) -> String {
if opts.redact_text
&& let Some(map) = redaction
&& !map.is_empty()
{
return map.redacted_plain_text(screen);
}
if opts.strip_ansi {
screen
.rows(0, cols)
.collect::<Vec<String>>()
.join("\n")
.trim_end()
.to_string()
} else if opts.from_screen {
screen_ansi_text(screen, cols)
} else {
String::from_utf8_lossy(data).trim_end().to_string()
}
}
fn description_text(
&self,
screen: &CapturedScreen,
cols: u16,
redaction: Option<&RedactionMap>,
opts: TextOptions,
) -> Option<String> {
if !opts.embed_description {
return None;
}
if let Some(map) = redaction
&& !map.is_empty()
{
return Some(map.redacted_plain_text(screen));
}
Some(
screen
.rows(0, cols)
.collect::<Vec<String>>()
.join("\n")
.trim_end()
.to_string(),
)
}
#[allow(clippy::too_many_arguments)]
fn render_to_image(
&self,
screen: &CapturedScreen,
theme: &Theme,
fonts: &ThemeFonts,
chrome: &ChromeOptions,
redaction: Option<&RedactionMap>,
auto_crop: bool,
) -> Result<RgbaImage> {
let layout = self.screen_layout(screen, fonts, auto_crop);
if chrome.enabled {
let metrics = ChromeMetrics::new(
chrome,
layout.width,
layout.height,
self.timestamp_reserve(fonts),
);
metrics.check_budget(screen)?;
return Ok(self.compose_with_chrome_layer(
theme,
fonts,
chrome,
&metrics,
|renderer, frame, x, y| {
renderer.draw_screen_into(frame, x, y, &layout, screen, theme, fonts, redaction)
},
));
}
let mut img = self.render_screen(screen, theme, fonts, redaction, auto_crop)?;
if chrome.rounded {
self.round_image_corners(&mut img, chrome.radius * RENDER_SCALE);
}
Ok(img)
}
fn screen_layout(
&self,
screen: &CapturedScreen,
fonts: &ThemeFonts,
auto_crop: bool,
) -> ScreenLayout {
let rows = screen.size().0 as u32;
let cols = screen.size().1 as u32;
let content_rows = self.find_content_rows(screen, rows, cols);
let content_cols = if auto_crop {
self.find_content_cols(screen, content_rows, cols)
} else {
cols
};
let scale = RENDER_SCALE;
let cell_w = fonts.cell_width * scale;
let cell_h = fonts.cell_height * scale;
let padding = self.padding * scale;
ScreenLayout {
content_rows,
content_cols,
cell_w,
cell_h,
padding,
width: content_cols * cell_w + padding * 2,
height: content_rows * cell_h + padding * 2,
}
}
fn render_screen(
&self,
screen: &CapturedScreen,
theme: &Theme,
fonts: &ThemeFonts,
redaction: Option<&RedactionMap>,
auto_crop: bool,
) -> Result<RgbaImage> {
let layout = self.screen_layout(screen, fonts, auto_crop);
check_render_budget(layout.width, layout.height, 1, screen)?;
let mut img: RgbaImage =
ImageBuffer::from_pixel(layout.width, layout.height, theme.background);
self.draw_screen_into(&mut img, 0, 0, &layout, screen, theme, fonts, redaction);
Ok(img)
}
#[allow(clippy::too_many_arguments)]
fn draw_screen_into(
&self,
img: &mut RgbaImage,
ox: u32,
oy: u32,
layout: &ScreenLayout,
screen: &CapturedScreen,
theme: &Theme,
fonts: &ThemeFonts,
redaction: Option<&RedactionMap>,
) {
let ScreenLayout {
content_rows,
content_cols,
cell_w,
cell_h,
padding,
width,
height,
} = *layout;
let hi_font_size = self.font_size * RENDER_SCALE as f32;
self.draw_rect(img, ox, oy, width, height, theme.background);
let shaping = fonts.shaping.enabled();
for row in 0..content_rows {
let mut unshapable_until = 0u32;
let mut col = 0u32;
while col < content_cols {
let Some(cell) = screen.cell(row as u16, col as u16) else {
col += 1;
continue;
};
let x = ox + col * cell_w + padding;
let y = oy + row * cell_h + padding;
if let Some(rc) = redaction.and_then(|m| m.get(row as u16, col as u16)) {
let block =
Rgba([rc.block_color[0], rc.block_color[1], rc.block_color[2], 255]);
self.draw_rect(img, x, y, cell_w, cell_h, block);
if let Some(label_ch) = rc.label_char {
let label =
Rgba([rc.label_color[0], rc.label_color[1], rc.label_color[2], 255]);
self.draw_char_with_font(
img,
fonts,
x,
y,
label_ch,
label,
false,
hi_font_size,
&self.font_for_char(fonts, label_ch, false, hi_font_size),
cell_w,
);
}
col += 1;
continue;
}
if shaping && col >= unshapable_until && self.cell_needs_shaping(fonts, cell) {
let run =
self.collect_shaped_run(screen, fonts, row, col, content_cols, redaction);
if self
.draw_shaped_run(img, fonts, theme, screen, row, col, &run, layout, ox, oy)
{
col += run.cols;
continue;
}
unshapable_until = col + run.cols;
}
self.draw_cell(img, fonts, theme, cell, x, y, cell_w, cell_h, hi_font_size);
col += 1;
}
}
}
#[allow(clippy::too_many_arguments)]
fn draw_cell(
&self,
img: &mut RgbaImage,
fonts: &ThemeFonts,
theme: &Theme,
cell: &vt100::Cell,
x: u32,
y: u32,
cell_w: u32,
cell_h: u32,
hi_font_size: f32,
) {
let (fg_color, bg_color) = self.resolve_cell_colors(cell, theme);
if bg_color != theme.background {
self.draw_rect(img, x, y, cell_w, cell_h, bg_color);
}
let ch = cell.contents();
if !ch.is_empty() && ch != " " {
let cell_span = if cell.is_wide() { cell_w * 2 } else { cell_w };
let bold = cell.bold();
let has_bold_font = fonts.font_bold.is_some();
for c in ch.chars() {
let chosen = self.font_for_char(fonts, c, bold, hi_font_size);
self.draw_char_with_font(
img,
fonts,
x,
y,
c,
fg_color,
cell.italic(),
hi_font_size,
&chosen,
cell_span,
);
if bold && !has_bold_font {
self.draw_char_with_font(
img,
fonts,
x + 1,
y,
c,
fg_color,
cell.italic(),
hi_font_size,
&chosen,
cell_span,
);
}
}
}
if cell.underline() {
let uy = y + cell_h.saturating_sub(2 * RENDER_SCALE);
self.draw_rect(img, x, uy, cell_w, RENDER_SCALE, fg_color);
}
}
fn cell_needs_shaping(&self, fonts: &ThemeFonts, cell: &vt100::Cell) -> bool {
let contents = cell.contents();
if contents.is_empty() || contents == " " {
return false;
}
let mut chars = contents.chars();
let Some(first) = chars.next() else {
return false;
};
if chars.next().is_some() {
return true;
}
if unicode::cluster_is_emoji(contents) {
return true;
}
if unicode::script_needs_shaping(first.script()) {
return true;
}
let hi_font_size = self.font_size * RENDER_SCALE as f32;
!fonts.chain_covers(first, cell.bold(), hi_font_size)
}
fn collect_shaped_run(
&self,
screen: &CapturedScreen,
fonts: &ThemeFonts,
row: u32,
col: u32,
content_cols: u32,
redaction: Option<&RedactionMap>,
) -> ShapedRunSpan {
let mut cells = Vec::new();
let mut cols = 0u32;
let mut style = None;
let mut class = None;
let mut at = col;
while at < content_cols {
let Some(cell) = screen.cell(row as u16, at as u16) else {
break;
};
let wide = cell.is_wide() && at + 1 < content_cols;
let span = if wide { 2 } else { 1 };
if (0..span).any(|offset| {
redaction
.and_then(|map| map.get(row as u16, (at + offset) as u16))
.is_some()
}) {
break;
}
let cell_style = CellStyle::of(cell);
match style {
None => style = Some(cell_style),
Some(first) if first == cell_style => {}
Some(_) => break,
}
if !self.cell_needs_shaping(fonts, cell) {
let bridges_contiguous_phrase = class == Some((false, true))
&& cell.contents() == " "
&& self.contiguous_shaping_resumes(
screen,
fonts,
row,
at + span,
content_cols,
redaction,
cell_style,
);
if bridges_contiguous_phrase {
cells.push(RunCell {
text: cell.contents().to_string(),
cols: span,
});
cols += span;
at += span;
continue;
}
break;
}
let contents = cell.contents();
let cell_class = (
unicode::cluster_is_emoji(contents),
unicode::cluster_forces_contiguous_run(contents),
);
match class {
None => class = Some(cell_class),
Some(first) if first == cell_class => {}
Some(_) => break,
}
cells.push(RunCell {
text: contents.to_string(),
cols: span,
});
cols += span;
at += span;
}
ShapedRunSpan { cells, cols }
}
#[allow(clippy::too_many_arguments)]
fn contiguous_shaping_resumes(
&self,
screen: &CapturedScreen,
fonts: &ThemeFonts,
row: u32,
mut at: u32,
content_cols: u32,
redaction: Option<&RedactionMap>,
style: CellStyle,
) -> bool {
while at < content_cols {
let Some(cell) = screen.cell(row as u16, at as u16) else {
return false;
};
let span = if cell.is_wide() && at + 1 < content_cols {
2
} else {
1
};
if (0..span).any(|offset| {
redaction
.and_then(|map| map.get(row as u16, (at + offset) as u16))
.is_some()
}) || CellStyle::of(cell) != style
{
return false;
}
if cell.contents() == " " {
at += span;
continue;
}
return self.cell_needs_shaping(fonts, cell)
&& !unicode::cluster_is_emoji(cell.contents())
&& unicode::cluster_forces_contiguous_run(cell.contents());
}
false
}
#[allow(clippy::too_many_arguments)]
fn draw_shaped_run(
&self,
img: &mut RgbaImage,
fonts: &ThemeFonts,
theme: &Theme,
screen: &CapturedScreen,
row: u32,
col: u32,
run: &ShapedRunSpan,
layout: &ScreenLayout,
ox: u32,
oy: u32,
) -> bool {
if run.cells.is_empty() {
return false;
}
let ScreenLayout {
cell_w,
cell_h,
padding,
..
} = *layout;
let Some(first) = screen.cell(row as u16, col as u16) else {
return false;
};
let hi_font_size = self.font_size * RENDER_SCALE as f32;
let bold = first.bold();
let has_bold_font = fonts.font_bold.is_some();
let request = RunRequest {
cells: &run.cells,
cell_w,
font_size: hi_font_size,
ascent: font_ascent(&fonts.font, hi_font_size),
bold: bold && has_bold_font,
italic: first.italic(),
};
let placed = fonts.shaping.place_run(&request);
if placed.is_empty() {
return false;
}
let run_x = ox + col * cell_w + padding;
let run_y = oy + row * cell_h + padding;
let (fg_color, _) = self.resolve_cell_colors(first, theme);
for offset in 0..run.cols {
let Some(cell) = screen.cell(row as u16, (col + offset) as u16) else {
continue;
};
let (_, bg_color) = self.resolve_cell_colors(cell, theme);
if bg_color != theme.background {
self.draw_rect(
img,
run_x + offset * cell_w,
run_y,
cell_w,
cell_h,
bg_color,
);
}
}
let clip = ClipRect {
x0: run_x as i32,
x1: (run_x + run.cols * cell_w) as i32,
y0: run_y as i32,
y1: (run_y + cell_h) as i32,
};
for glyph in &placed {
self.blend_glyph_bitmap(
img,
run_x as i32 + glyph.x,
run_y as i32 + glyph.y,
&glyph.bitmap,
fg_color,
clip,
);
if bold && !has_bold_font {
self.blend_glyph_bitmap(
img,
run_x as i32 + glyph.x + 1,
run_y as i32 + glyph.y,
&glyph.bitmap,
fg_color,
clip,
);
}
}
for offset in 0..run.cols {
let Some(cell) = screen.cell(row as u16, (col + offset) as u16) else {
continue;
};
if cell.underline() {
let (cell_fg, _) = self.resolve_cell_colors(cell, theme);
let uy = run_y + cell_h.saturating_sub(2 * RENDER_SCALE);
self.draw_rect(
img,
run_x + offset * cell_w,
uy,
cell_w,
RENDER_SCALE,
cell_fg,
);
}
}
true
}
fn blend_glyph_bitmap(
&self,
img: &mut RgbaImage,
x: i32,
y: i32,
bitmap: &GlyphBitmap,
color: Rgba<u8>,
clip: ClipRect,
) {
for gy in 0..bitmap.height {
let py = y + gy as i32;
if py < clip.y0 || py >= clip.y1 || py < 0 || py as u32 >= img.height() {
continue;
}
for gx in 0..bitmap.width {
let px = x + gx as i32;
if px < clip.x0 || px >= clip.x1 || px < 0 || px as u32 >= img.width() {
continue;
}
let index = (gy * bitmap.width + gx) as usize;
let pixel = if bitmap.color {
let at = index * 4;
let Some(rgba) = bitmap.data.get(at..at + 4) else {
continue;
};
if rgba[3] == 0 {
continue;
}
Rgba([
rgba[0],
rgba[1],
rgba[2],
((rgba[3] as u32 * color[3] as u32) / 255) as u8,
])
} else {
let Some(&coverage) = bitmap.data.get(index) else {
continue;
};
if coverage == 0 {
continue;
}
Rgba([
color[0],
color[1],
color[2],
((coverage as u32 * color[3] as u32) / 255) as u8,
])
};
self.put_pixel_blend(img, px as u32, py as u32, pixel);
}
}
}
fn compose_with_chrome(
&self,
terminal: RgbaImage,
theme: &Theme,
fonts: &ThemeFonts,
chrome: &ChromeOptions,
) -> RgbaImage {
if !chrome.enabled {
return terminal;
}
let metrics = ChromeMetrics::new(
chrome,
terminal.width(),
terminal.height(),
self.timestamp_reserve(fonts),
);
self.compose_with_chrome_layer(theme, fonts, chrome, &metrics, |_, frame, ox, oy| {
for y in 0..terminal.height() {
for x in 0..terminal.width() {
frame.put_pixel(ox + x, oy + y, *terminal.get_pixel(x, y));
}
}
})
}
fn compose_with_chrome_layer(
&self,
theme: &Theme,
fonts: &ThemeFonts,
chrome: &ChromeOptions,
metrics: &ChromeMetrics,
draw_terminal: impl FnOnce(&Self, &mut RgbaImage, u32, u32),
) -> RgbaImage {
let scale = RENDER_SCALE;
let &ChromeMetrics {
radius,
title_bar,
shadow,
frame_pad,
bottom_pad,
frame_w,
frame_h,
term_h,
width,
height,
} = metrics;
let frame_bg = theme.background;
let mut frame: RgbaImage = ImageBuffer::from_pixel(frame_w, frame_h, frame_bg);
if title_bar > 0 {
let title_bg = match chrome.preset.as_str() {
"macos" => Rgba([44, 44, 46, 255]),
"gnome" => Rgba([32, 34, 39, 255]),
"report" => Rgba([30, 32, 36, 255]),
_ => Rgba([
theme.background[0].saturating_add(10),
theme.background[1].saturating_add(10),
theme.background[2].saturating_add(10),
255,
]),
};
self.draw_rect(&mut frame, 0, 0, frame_w, title_bar, title_bg);
self.draw_title_bar_accents(&mut frame, chrome, 0, 0, frame_w, title_bar, theme, scale);
if let Some(title) = chrome.title.as_deref() {
let title = truncate_title(title);
self.draw_text_line(
&mut frame,
fonts,
frame_w / 2,
title_bar / 2,
&title,
theme.foreground,
self.font_size * 0.85 * scale as f32,
);
}
}
let term_x = frame_pad;
let term_y = frame_pad + title_bar;
draw_terminal(self, &mut frame, term_x, term_y);
if chrome.timestamp {
let timestamp = Utc::now().format("%Y-%m-%d %H:%M:%S UTC").to_string();
let color = muted_text_color(theme);
let right_x = frame_w.saturating_sub(frame_pad.max(6 * scale));
let center_y = term_y + term_h + bottom_pad / 2;
self.draw_text_right_aligned(
&mut frame,
fonts,
right_x,
center_y,
×tamp,
color,
self.timestamp_font_size(),
);
}
self.round_image_corners(&mut frame, radius);
if shadow == 0 {
return frame;
}
let mut img: RgbaImage = ImageBuffer::from_pixel(width, height, Rgba([0, 0, 0, 0]));
let frame_x = shadow / 2;
let frame_y = shadow / 2;
self.draw_shadow(
&mut img,
frame_x,
frame_y,
frame_w,
frame_h,
radius,
4 * scale,
6 * scale,
12 * scale,
);
for y in 0..frame.height() {
for x in 0..frame.width() {
let px = *frame.get_pixel(x, y);
if px[3] == 0 {
continue;
}
self.put_pixel_blend(&mut img, frame_x + x, frame_y + y, px);
}
}
img
}
#[allow(clippy::too_many_arguments)]
fn draw_shadow(
&self,
img: &mut RgbaImage,
frame_x: u32,
frame_y: u32,
frame_w: u32,
frame_h: u32,
radius: u32,
offset_x: u32,
offset_y: u32,
blur: u32,
) {
if frame_w == 0 || frame_h == 0 || blur == 0 {
return;
}
const PEAK_ALPHA: f32 = 110.0;
let (img_w, img_h) = img.dimensions();
let shadow_x = (frame_x + offset_x) as f32;
let shadow_y = (frame_y + offset_y) as f32;
let (sw, sh) = (frame_w as f32, frame_h as f32);
let r = (radius as f32).min(sw / 2.0).min(sh / 2.0);
let sdf = |px: f32, py: f32| -> f32 {
let cx = shadow_x + sw / 2.0;
let cy = shadow_y + sh / 2.0;
let qx = (px - cx).abs() - (sw / 2.0 - r);
let qy = (py - cy).abs() - (sh / 2.0 - r);
let outside = (qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt();
outside + qx.max(qy).min(0.0) - r
};
let skip_x0 = frame_x + radius;
let skip_x1 = frame_x + frame_w.saturating_sub(radius);
let skip_y0 = frame_y + radius;
let skip_y1 = frame_y + frame_h.saturating_sub(radius);
let y0 = frame_y.saturating_sub(blur);
let y1 = (frame_y + frame_h + offset_y + blur).min(img_h);
let x0 = frame_x.saturating_sub(blur);
let x1 = (frame_x + frame_w + offset_x + blur).min(img_w);
let blur_f = blur as f32;
for py in y0..y1 {
let inside_y = py >= skip_y0 && py < skip_y1;
for px in x0..x1 {
if inside_y && px >= skip_x0 && px < skip_x1 {
continue;
}
let d = sdf(px as f32 + 0.5, py as f32 + 0.5);
if d >= blur_f {
continue;
}
let t = (1.0 - (d.max(0.0) / blur_f)).clamp(0.0, 1.0);
let alpha = (PEAK_ALPHA * t * t * (3.0 - 2.0 * t)).round() as u8;
if alpha == 0 {
continue;
}
self.put_pixel_blend(img, px, py, Rgba([0, 0, 0, alpha]));
}
}
}
fn round_image_corners(&self, img: &mut RgbaImage, radius: u32) {
let (w, h) = img.dimensions();
if radius == 0 || w == 0 || h == 0 {
return;
}
let radius = radius.min(w / 2).min(h / 2);
if radius == 0 {
return;
}
let r = radius as f32;
let (wf, hf) = (w as f32, h as f32);
for py in 0..h {
let fy = py as f32 + 0.5;
let dy = if fy < r {
r - fy
} else if fy > hf - r {
fy - (hf - r)
} else {
0.0
};
for px in 0..w {
let fx = px as f32 + 0.5;
let dx = if fx < r {
r - fx
} else if fx > wf - r {
fx - (wf - r)
} else {
0.0
};
if dx == 0.0 || dy == 0.0 {
continue;
}
let dist = (dx * dx + dy * dy).sqrt();
let coverage = (r + 0.5 - dist).clamp(0.0, 1.0);
if coverage >= 1.0 {
continue;
}
let pixel = img.get_pixel_mut(px, py);
pixel[3] = (pixel[3] as f32 * coverage).round() as u8;
}
}
}
#[allow(clippy::too_many_arguments)]
fn draw_rounded_rect(
&self,
img: &mut RgbaImage,
x: u32,
y: u32,
w: u32,
h: u32,
radius: u32,
color: Rgba<u8>,
) {
if w == 0 || h == 0 || color[3] == 0 {
return;
}
let r = radius.min(w / 2).min(h / 2) as f32;
let (half_w, half_h) = (w as f32 / 2.0, h as f32 / 2.0);
let (center_x, center_y) = (x as f32 + half_w, y as f32 + half_h);
for py in y..(y + h).min(img.height()) {
let qy = ((py as f32 + 0.5) - center_y).abs() - (half_h - r);
for px in x..(x + w).min(img.width()) {
let qx = ((px as f32 + 0.5) - center_x).abs() - (half_w - r);
let distance =
(qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt() + qx.max(qy).min(0.0) - r;
let coverage = (0.5 - distance).clamp(0.0, 1.0);
if coverage <= 0.0 {
continue;
}
let alpha = (color[3] as f32 * coverage).round().clamp(0.0, 255.0) as u8;
if alpha == 0 {
continue;
}
self.put_pixel_blend(img, px, py, Rgba([color[0], color[1], color[2], alpha]));
}
}
}
#[allow(clippy::too_many_arguments)]
fn draw_title_bar_accents(
&self,
img: &mut RgbaImage,
chrome: &ChromeOptions,
frame_x: u32,
frame_y: u32,
width: u32,
title_bar_height: u32,
theme: &Theme,
scale: u32,
) {
match chrome.preset.as_str() {
"macos" => {
let colors = [
Rgba([255, 95, 86, 255]),
Rgba([255, 189, 46, 255]),
Rgba([39, 201, 63, 255]),
];
let radius = TRAFFIC_LIGHT_RADIUS * scale;
let center_y = frame_y as f32 + title_bar_height as f32 / 2.0;
for (i, color) in colors.into_iter().enumerate() {
let center_x = (frame_x
+ (TRAFFIC_LIGHT_FIRST_CENTER + i as u32 * TRAFFIC_LIGHT_PITCH) * scale)
as f32;
self.draw_circle(img, center_x, center_y, radius as f32, color);
}
}
"gnome" => {
let pill_w = 44 * scale;
let pill_h = 14 * scale;
let pill_x = frame_x + width.saturating_sub(16 * scale + pill_w);
let pill_y = frame_y + (title_bar_height / 2).saturating_sub(pill_h / 2);
self.draw_rounded_rect(
img,
pill_x,
pill_y,
pill_w,
pill_h,
7 * scale,
Rgba([255, 255, 255, 24]),
);
for offset in [12u32, 22, 32] {
self.draw_circle(
img,
(pill_x + offset * scale) as f32,
(pill_y + pill_h / 2) as f32,
(2 * scale) as f32,
Rgba([255, 255, 255, 90]),
);
}
}
"report" => {
self.draw_rect(
img,
frame_x,
frame_y + title_bar_height.saturating_sub(scale),
width,
scale,
Rgba([255, 255, 255, 20]),
);
}
_ => {
let accent = Rgba([
theme.foreground[0],
theme.foreground[1],
theme.foreground[2],
18,
]);
self.draw_rect(
img,
frame_x,
frame_y + title_bar_height.saturating_sub(scale),
width,
scale,
accent,
);
}
}
}
fn draw_circle(&self, img: &mut RgbaImage, cx: f32, cy: f32, r: f32, color: Rgba<u8>) {
if r <= 0.0 || color[3] == 0 {
return;
}
let (img_w, img_h) = img.dimensions();
let x0 = (cx - r - 1.0).floor().max(0.0) as u32;
let y0 = (cy - r - 1.0).floor().max(0.0) as u32;
let x1 = ((cx + r + 1.0).ceil().max(0.0) as u32).min(img_w);
let y1 = ((cy + r + 1.0).ceil().max(0.0) as u32).min(img_h);
for py in y0..y1 {
let dy = py as f32 + 0.5 - cy;
for px in x0..x1 {
let dx = px as f32 + 0.5 - cx;
let distance = (dx * dx + dy * dy).sqrt();
let coverage = (r + 0.5 - distance).clamp(0.0, 1.0);
if coverage <= 0.0 {
continue;
}
let alpha = (color[3] as f32 * coverage).round().clamp(0.0, 255.0) as u8;
if alpha == 0 {
continue;
}
self.put_pixel_blend(img, px, py, Rgba([color[0], color[1], color[2], alpha]));
}
}
}
#[allow(clippy::too_many_arguments)]
fn draw_text_line(
&self,
img: &mut RgbaImage,
fonts: &ThemeFonts,
center_x: u32,
center_y: u32,
text: &str,
color: Rgba<u8>,
size: f32,
) {
let total_width = self.text_width(fonts, text, size);
self.draw_text_at(
img,
fonts,
center_x as i32 - (total_width as i32 / 2),
center_y,
text,
color,
size,
);
}
#[allow(clippy::too_many_arguments)]
fn draw_text_right_aligned(
&self,
img: &mut RgbaImage,
fonts: &ThemeFonts,
right_x: u32,
center_y: u32,
text: &str,
color: Rgba<u8>,
size: f32,
) {
let total_width = self.text_width(fonts, text, size);
self.draw_text_at(
img,
fonts,
right_x as i32 - total_width as i32,
center_y,
text,
color,
size,
);
}
fn timestamp_font_size(&self) -> f32 {
self.font_size * TIMESTAMP_FONT_SCALE * RENDER_SCALE as f32
}
fn timestamp_reserve(&self, fonts: &ThemeFonts) -> u32 {
let line_height = font_line_height(&fonts.font, self.timestamp_font_size()).ceil() as u32;
line_height + TIMESTAMP_GAP * RENDER_SCALE * 2
}
fn text_width(&self, fonts: &ThemeFonts, text: &str, size: f32) -> u32 {
let cell_advance = fonts.font.metrics('M', size).advance_width.round() as u32;
text.chars().count() as u32 * cell_advance
}
#[allow(clippy::too_many_arguments)]
fn draw_text_at(
&self,
img: &mut RgbaImage,
fonts: &ThemeFonts,
start_x: i32,
center_y: u32,
text: &str,
color: Rgba<u8>,
size: f32,
) {
let cell_advance = fonts.font.metrics('M', size).advance_width.round() as i32;
let line_height = font_line_height(&fonts.font, size);
let line_top = center_y as i32 - (line_height as i32 / 2);
let mut cursor_x = start_x;
for ch in text.chars() {
let chosen = self.font_for_char(fonts, ch, false, size);
let advance = cell_advance.max(0) as u32;
let (render_size, placement) = if chosen.is_fallback {
(
fallback_font_size(chosen.font, ch, size, advance),
GlyphPlacement::fallback(font_ascent(&fonts.font, size), advance),
)
} else {
(size, GlyphPlacement::natural())
};
self.draw_glyph(
img,
cursor_x,
line_top,
ch,
color,
false,
render_size,
chosen.font,
placement,
);
cursor_x += cell_advance;
}
}
fn find_content_rows(&self, screen: &CapturedScreen, rows: u32, cols: u32) -> u32 {
let mut last_row_with_content = 0u32;
for row in 0..rows {
for col in 0..cols {
if screen
.cell(row as u16, col as u16)
.is_some_and(cell_has_content)
{
last_row_with_content = row + 1;
break;
}
}
}
last_row_with_content.max(MIN_CONTENT_ROWS).min(rows)
}
fn find_content_cols(&self, screen: &CapturedScreen, rows: u32, cols: u32) -> u32 {
let mut max_col = 0u32;
for row in 0..rows {
for col in (0..cols).rev() {
if let Some(cell) = screen.cell(row as u16, col as u16)
&& cell_has_content(cell)
{
let end = if cell.is_wide() { col + 2 } else { col + 1 };
max_col = max_col.max(end.min(cols));
break;
}
}
}
max_col.clamp(MIN_CONTENT_COLS.min(cols), cols)
}
fn resolve_cell_colors(&self, cell: &vt100::Cell, theme: &Theme) -> (Rgba<u8>, Rgba<u8>) {
let mut fg = self.resolve_color(cell.fgcolor(), true, theme);
let mut bg = self.resolve_color(cell.bgcolor(), false, theme);
if cell.inverse() {
std::mem::swap(&mut fg, &mut bg);
}
if cell.bold() {
fg = match cell.fgcolor() {
vt100::Color::Idx(idx) if idx < 8 => theme.palette[(idx + 8) as usize],
vt100::Color::Default => theme.palette[15], _ => {
Rgba([
fg[0].saturating_add((255 - fg[0]) / 4),
fg[1].saturating_add((255 - fg[1]) / 4),
fg[2].saturating_add((255 - fg[2]) / 4),
fg[3],
])
}
};
}
if cell.dim() {
fg = Rgba([fg[0] / 2, fg[1] / 2, fg[2] / 2, fg[3]]);
}
(fg, bg)
}
fn resolve_color(&self, color: vt100::Color, is_foreground: bool, theme: &Theme) -> Rgba<u8> {
match color {
vt100::Color::Default => {
if is_foreground {
theme.foreground
} else {
theme.background
}
}
vt100::Color::Idx(idx) => {
if idx < 16 {
theme.palette[idx as usize]
} else if idx < 232 {
let idx = idx - 16;
let r = (idx / 36) % 6;
let g = (idx / 6) % 6;
let b = idx % 6;
Rgba([
if r == 0 { 0 } else { 55 + 40 * r },
if g == 0 { 0 } else { 55 + 40 * g },
if b == 0 { 0 } else { 55 + 40 * b },
255,
])
} else {
let level = 8 + 10 * (idx - 232);
Rgba([level, level, level, 255])
}
}
vt100::Color::Rgb(r, g, b) => Rgba([r, g, b, 255]),
}
}
fn draw_rect(&self, img: &mut RgbaImage, x: u32, y: u32, w: u32, h: u32, color: Rgba<u8>) {
for dy in 0..h {
for dx in 0..w {
let px = x + dx;
let py = y + dy;
if px < img.width() && py < img.height() {
self.put_pixel_blend(img, px, py, color);
}
}
}
}
fn put_pixel_blend(&self, img: &mut RgbaImage, x: u32, y: u32, color: Rgba<u8>) {
if color[3] == 255 {
img.put_pixel(x, y, color);
return;
}
if color[3] == 0 {
return;
}
let bg = img.get_pixel(x, y);
let src_a = color[3] as f32 / 255.0;
let dst_a = bg[3] as f32 / 255.0;
let out_a = src_a + dst_a * (1.0 - src_a);
if out_a <= 0.0 {
img.put_pixel(x, y, Rgba([0, 0, 0, 0]));
return;
}
let blend = |sc: u8, dc: u8| -> u8 {
let v = (sc as f32 * src_a + dc as f32 * dst_a * (1.0 - src_a)) / out_a;
v.round().clamp(0.0, 255.0) as u8
};
let out = Rgba([
blend(color[0], bg[0]),
blend(color[1], bg[1]),
blend(color[2], bg[2]),
(out_a * 255.0).round().clamp(0.0, 255.0) as u8,
]);
img.put_pixel(x, y, out);
}
#[allow(clippy::too_many_arguments)]
fn draw_glyph(
&self,
img: &mut RgbaImage,
cell_x: i32,
line_top: i32,
ch: char,
color: Rgba<u8>,
italic: bool,
font_size: f32,
font: &Font,
placement: GlyphPlacement,
) {
let (metrics, bitmap) = font.rasterize(ch, font_size);
if bitmap.is_empty() || metrics.width == 0 || metrics.height == 0 {
return;
}
let ascent = placement
.ascent
.unwrap_or_else(|| font_ascent(font, font_size));
let glyph_x = match placement.center_width {
Some(width) => {
cell_x
+ ((width as f32 - metrics.advance_width) / 2.0).round() as i32
+ metrics.xmin
}
None => cell_x + metrics.xmin,
};
let glyph_y = line_top + ascent.round() as i32 - metrics.height as i32 - metrics.ymin;
let shear = |gy: usize| -> i32 {
if !italic {
return 0;
}
let from_bottom = metrics.height as i32 - gy as i32;
(from_bottom as f32 * 0.22) as i32
};
for gy in 0..metrics.height {
let dx_italic = shear(gy);
for gx in 0..metrics.width {
let coverage = bitmap[gy * metrics.width + gx];
if coverage == 0 {
continue;
}
let px = glyph_x + gx as i32 + dx_italic;
let py = glyph_y + gy as i32;
if px < 0 || py < 0 {
continue;
}
let (px, py) = (px as u32, py as u32);
if px >= img.width() || py >= img.height() {
continue;
}
let alpha = ((coverage as u32 * color[3] as u32) / 255) as u8;
self.put_pixel_blend(img, px, py, Rgba([color[0], color[1], color[2], alpha]));
}
}
}
#[allow(clippy::too_many_arguments)]
fn draw_char_with_font(
&self,
img: &mut RgbaImage,
fonts: &ThemeFonts,
x: u32,
y: u32,
ch: char,
color: Rgba<u8>,
italic: bool,
font_size: f32,
font: &ChosenFont<'_>,
cell_span: u32,
) {
let (render_size, placement) = if font.is_fallback {
(
fallback_font_size(font.font, ch, font_size, cell_span),
GlyphPlacement::fallback(font_ascent(&fonts.font, font_size), cell_span),
)
} else {
(font_size, GlyphPlacement::natural())
};
self.draw_glyph(
img,
x as i32,
y as i32,
ch,
color,
italic,
render_size,
font.font,
placement,
);
}
fn font_for_char<'f>(
&self,
fonts: &'f ThemeFonts,
ch: char,
bold: bool,
font_size: f32,
) -> ChosenFont<'f> {
let primary = match (bold, fonts.font_bold.as_ref()) {
(true, Some(bold_font)) => bold_font,
_ => &fonts.font,
};
if font_covers(primary, ch, font_size) {
return ChosenFont {
font: primary,
is_fallback: false,
};
}
for font in &fonts.fallback_fonts {
if font_covers(font, ch, font_size) {
return ChosenFont {
font,
is_fallback: true,
};
}
}
ChosenFont {
font: primary,
is_fallback: false,
}
}
}
const MAX_FILENAME_CHARS: usize = 60;
fn sanitize_base_name(input: &str) -> String {
let mut out = String::new();
let mut pending_hyphen = false;
for ch in input.chars() {
if ch.is_ascii_alphanumeric() {
if pending_hyphen && !out.is_empty() {
out.push('-');
}
pending_hyphen = false;
out.push(ch.to_ascii_lowercase());
} else {
pending_hyphen = true;
}
}
let mut out: String = out.chars().take(MAX_FILENAME_CHARS).collect();
while out.ends_with('-') {
out.pop();
}
if out.is_empty() {
"screenshot".to_string()
} else {
out
}
}
fn unique_png_path(output_dir: &Path, base: &str) -> PathBuf {
let first = output_dir.join(format!("{}.png", base));
if !first.exists() {
return first;
}
let mut n = 2u32;
loop {
let candidate = output_dir.join(format!("{}-{}.png", base, n));
if !candidate.exists() {
return candidate;
}
n += 1;
}
}
pub fn fallback_output_name(cwd: Option<&Path>, command: &str) -> String {
let dir = cwd
.and_then(Path::file_name)
.map(|s| s.to_string_lossy().into_owned())
.unwrap_or_default();
let first = command.split_whitespace().next().unwrap_or("");
match (dir.trim().is_empty(), first.is_empty()) {
(false, false) => format!("{} {}", dir, first),
(true, false) => first.to_string(),
(false, true) => dir,
(true, true) => String::new(),
}
}
fn truncate_title(title: &str) -> String {
if title.chars().count() <= MAX_TITLE_CHARS {
return title.to_string();
}
format!(
"{}...",
title.chars().take(MAX_TITLE_CHARS).collect::<String>()
)
}
fn is_light(color: Rgba<u8>) -> bool {
let luminance = 0.2126 * color[0] as f32 + 0.7152 * color[1] as f32 + 0.0722 * color[2] as f32;
luminance > 150.0
}
fn muted_text_color(theme: &Theme) -> Rgba<u8> {
if is_light(theme.background) {
Rgba([0, 0, 0, 128])
} else {
Rgba([255, 255, 255, 128])
}
}
#[derive(Debug, Clone, Copy)]
struct ScreenLayout {
content_rows: u32,
content_cols: u32,
cell_w: u32,
cell_h: u32,
padding: u32,
width: u32,
height: u32,
}
struct ShapedRunSpan {
cells: Vec<RunCell>,
cols: u32,
}
#[derive(Debug, Clone, Copy)]
struct ClipRect {
x0: i32,
x1: i32,
y0: i32,
y1: i32,
}
#[derive(Debug, Clone, Copy)]
struct ChromeMetrics {
radius: u32,
title_bar: u32,
shadow: u32,
frame_pad: u32,
bottom_pad: u32,
frame_w: u32,
frame_h: u32,
term_h: u32,
width: u32,
height: u32,
}
impl ChromeMetrics {
fn new(chrome: &ChromeOptions, term_w: u32, term_h: u32, timestamp_reserve: u32) -> Self {
let scale = RENDER_SCALE;
let radius = if chrome.rounded {
chrome.radius * scale
} else {
0
};
let title_bar = match chrome.preset.as_str() {
"minimal" => 0,
_ => chrome.title_bar_height * scale,
};
let shadow = if chrome.shadow { 16 * scale } else { 0 };
let frame_pad = chrome.outer_padding * scale;
let bottom_pad = if chrome.timestamp {
frame_pad.max(timestamp_reserve)
} else {
frame_pad
};
let frame_w = term_w + frame_pad * 2;
let frame_h = term_h + frame_pad + bottom_pad + title_bar;
Self {
radius,
title_bar,
shadow,
frame_pad,
bottom_pad,
frame_w,
frame_h,
term_h,
width: frame_w + shadow,
height: frame_h + shadow,
}
}
fn check_budget(&self, screen: &CapturedScreen) -> Result<()> {
let layers = if self.shadow > 0 { 2 } else { 1 };
check_render_budget(self.width, self.height, layers, screen)
}
}
fn check_render_budget(
width: u32,
height: u32,
layers: u64,
screen: &CapturedScreen,
) -> Result<()> {
let pixels = u64::from(width) * u64::from(height);
let bytes = pixels * BYTES_PER_PIXEL * layers;
let reason = if pixels > MAX_IMAGE_PIXELS {
format!(
"{} megapixels, over the {} megapixel limit",
pixels / 1_000_000,
MAX_IMAGE_PIXELS / 1_000_000
)
} else if bytes > MAX_RENDER_BYTES {
format!(
"about {} MB of image buffers, over the {} MB limit",
bytes / (1024 * 1024),
MAX_RENDER_BYTES / (1024 * 1024)
)
} else {
return Ok(());
};
anyhow::bail!(
"the capture would render as a {}x{} px image, needing {}: it holds {} lines of \
output. Narrow it with --head-lines/--tail-lines (head_lines/tail_lines over MCP), \
or use fewer columns.",
width,
height,
reason,
screen.size().0
);
}
#[cfg(test)]
mod tests {
use super::*;
fn screen_of(data: &[u8], rows: u16, cols: u16) -> CapturedScreen {
CapturedScreen::parse(data, rows, cols, 0)
}
#[test]
fn chrome_options_from_config_respects_enabled_and_preset() {
let config = ChromeConfig {
enabled: true,
preset: "gnome".to_string(),
title: Some("demo".to_string()),
timestamp: false,
shadow: true,
radius: 12,
rounded: true,
outer_padding: 20,
title_bar_height: 30,
};
let options = ChromeOptions::from_config(&config);
assert!(options.enabled);
assert_eq!(options.preset, "gnome");
assert_eq!(options.title.as_deref(), Some("demo"));
assert!(!options.timestamp);
}
#[test]
fn compose_with_chrome_increases_canvas_size() {
let renderer = renderer_with_chrome(ChromeOptions {
enabled: false,
preset: "none".to_string(),
title: None,
timestamp: false,
shadow: true,
radius: 14,
rounded: true,
outer_padding: 18,
title_bar_height: 34,
});
let terminal = ImageBuffer::from_pixel(100, 50, Rgba([10, 10, 10, 255]));
let theme = Theme::dark();
let chrome = ChromeOptions {
enabled: true,
preset: "gnome".to_string(),
title: Some("demo".to_string()),
timestamp: false,
shadow: true,
radius: 14,
rounded: true,
outer_padding: 18,
title_bar_height: 34,
};
let result =
renderer.compose_with_chrome(terminal, &theme, &renderer.default_fonts, &chrome);
assert!(result.width() > 100);
assert!(result.height() > 50);
}
#[test]
fn timestamp_reserves_bottom_padding() {
let renderer = renderer_with_chrome(ChromeOptions {
enabled: false,
preset: "none".to_string(),
title: None,
timestamp: false,
shadow: false,
radius: 14,
rounded: true,
outer_padding: 0,
title_bar_height: 34,
});
let terminal = ImageBuffer::from_pixel(100, 50, Rgba([10, 10, 10, 255]));
let chrome = ChromeOptions {
enabled: true,
preset: "report".to_string(),
title: None,
timestamp: true,
shadow: false,
radius: 14,
rounded: true,
outer_padding: 0,
title_bar_height: 34,
};
let result = renderer.compose_with_chrome(
terminal,
&Theme::dark(),
&renderer.default_fonts,
&chrome,
);
let reserve = renderer.timestamp_reserve(&renderer.default_fonts);
assert_eq!(result.height(), 50 + 68 + reserve);
let line_height =
font_line_height(&renderer.default_fonts.font, renderer.timestamp_font_size()).ceil()
as u32;
assert_eq!(reserve, line_height + TIMESTAMP_GAP * RENDER_SCALE * 2);
assert!(
reserve
< renderer.default_fonts.cell_height * RENDER_SCALE
+ renderer.padding * RENDER_SCALE,
"the timestamp reserve grew back into a blank terminal row: {reserve}"
);
}
#[test]
fn no_timestamp_reserves_no_extra_bottom_space() {
let renderer = bare_renderer();
let base = ChromeOptions {
enabled: true,
preset: "report".to_string(),
title: None,
timestamp: false,
shadow: false,
radius: 14,
rounded: true,
outer_padding: 0,
title_bar_height: 34,
};
let with_stamp = ChromeOptions {
timestamp: true,
..base.clone()
};
let compose = |chrome: &ChromeOptions| {
renderer.compose_with_chrome(
ImageBuffer::from_pixel(100, 50, Rgba([10, 10, 10, 255])),
&Theme::dark(),
&renderer.default_fonts,
chrome,
)
};
let plain = compose(&base);
assert_eq!(plain.height(), 50 + 34 * RENDER_SCALE);
assert_eq!(
compose(&with_stamp).height() - plain.height(),
renderer.timestamp_reserve(&renderer.default_fonts)
);
}
#[test]
fn timestamp_pixels_stay_inside_the_image() {
let mut renderer = bare_renderer();
renderer.themes.insert("dark".to_string(), Theme::dark());
let theme = Theme::dark();
let chrome = ChromeOptions {
enabled: true,
preset: "report".to_string(),
title: None,
timestamp: true,
shadow: false,
radius: 0,
rounded: false,
outer_padding: 0,
title_bar_height: 34,
};
let captured = screen_of(b"hello", 6, 40);
let img = renderer
.render_to_image(
&captured,
&theme,
&renderer.default_fonts,
&chrome,
None,
true,
)
.unwrap();
let layout = renderer.screen_layout(&captured, &renderer.default_fonts, true);
let reserve = renderer.timestamp_reserve(&renderer.default_fonts);
assert_eq!(
img.height(),
layout.height + 34 * RENDER_SCALE + reserve,
"the frame reserved something other than the timestamp strip"
);
let strip_top = img.height() - reserve;
let inked_rows: Vec<u32> = (strip_top..img.height())
.filter(|&y| (0..img.width()).any(|x| *img.get_pixel(x, y) != theme.background))
.collect();
assert!(
!inked_rows.is_empty(),
"the timestamp was not drawn in its reserved strip"
);
assert!(
*inked_rows.first().unwrap() > strip_top,
"timestamp ink touches the top of its reserve"
);
assert!(
*inked_rows.last().unwrap() < img.height() - 1,
"timestamp ink touches the bottom edge of the image"
);
}
#[test]
fn a_single_line_has_matching_top_and_bottom_padding() {
let renderer = bare_renderer();
let theme = Theme::dark();
let captured = screen_of(b"\x1b[41m \x1b[0m", 24, 80);
let img = renderer
.render_screen(&captured, &theme, &renderer.default_fonts, None, true)
.unwrap();
let cell_h = renderer.default_fonts.cell_height * RENDER_SCALE;
let padding = renderer.padding * RENDER_SCALE;
assert_eq!(img.height(), cell_h + padding * 2);
let inked = |y: u32| (0..img.width()).any(|x| *img.get_pixel(x, y) != theme.background);
let top = (0..img.height())
.find(|&y| inked(y))
.expect("content drawn");
let bottom = (0..img.height()).rev().find(|&y| inked(y)).unwrap();
let top_margin = top;
let bottom_margin = img.height() - 1 - bottom;
assert_eq!(top_margin, padding);
assert!(
(top_margin as i32 - bottom_margin as i32).abs() <= 1,
"asymmetric vertical padding: {top_margin}px above, {bottom_margin}px below"
);
}
#[test]
fn a_single_line_of_text_is_exactly_one_cell_tall() {
let renderer = renderer_with_measured_cells();
let theme = Theme::dark();
let captured = screen_of(b"hello, jq!", 24, 80);
let img = renderer
.render_screen(&captured, &theme, &renderer.default_fonts, None, true)
.unwrap();
let cell_h = renderer.default_fonts.cell_height * RENDER_SCALE;
let padding = renderer.padding * RENDER_SCALE;
assert_eq!(img.height(), cell_h + padding * 2);
let inked = |y: u32| (0..img.width()).any(|x| *img.get_pixel(x, y) != theme.background);
let top = (0..img.height()).find(|&y| inked(y)).expect("text drawn");
let bottom = (0..img.height()).rev().find(|&y| inked(y)).unwrap();
assert!(
top >= padding && bottom < padding + cell_h,
"glyph ink escaped its cell: rows {top}..={bottom} of {}",
img.height()
);
}
#[test]
fn multiple_lines_leave_no_blank_row_below_the_last_line() {
let renderer = bare_renderer();
let theme = Theme::dark();
let captured = screen_of(b"one\r\ntwo\r\nthree", 24, 80);
let img = renderer
.render_screen(&captured, &theme, &renderer.default_fonts, None, true)
.unwrap();
let cell_h = renderer.default_fonts.cell_height * RENDER_SCALE;
let padding = renderer.padding * RENDER_SCALE;
assert_eq!(img.height(), 3 * cell_h + padding * 2);
let inked = |y: u32| (0..img.width()).any(|x| *img.get_pixel(x, y) != theme.background);
let bottom = (0..img.height()).rev().find(|&y| inked(y)).unwrap();
assert!(
img.height() - 1 - bottom < padding + cell_h,
"a blank terminal row was kept below the last line"
);
}
#[test]
fn an_empty_capture_still_renders_one_row() {
let renderer = bare_renderer();
let theme = Theme::dark();
let captured = screen_of(b"", 24, 80);
let img = renderer
.render_screen(&captured, &theme, &renderer.default_fonts, None, true)
.unwrap();
let cell_h = renderer.default_fonts.cell_height * RENDER_SCALE;
let cell_w = renderer.default_fonts.cell_width * RENDER_SCALE;
let padding = renderer.padding * RENDER_SCALE;
assert_eq!(img.height(), cell_h + padding * 2);
assert_eq!(img.width(), cell_w + padding * 2);
}
#[test]
fn height_trim_keeps_a_trailing_styled_row() {
let renderer = bare_renderer();
let theme = Theme::dark();
let captured = screen_of(b"hi\r\n\x1b[42m \x1b[0m", 24, 80);
let img = renderer
.render_screen(&captured, &theme, &renderer.default_fonts, None, true)
.unwrap();
let cell_h = renderer.default_fonts.cell_height * RENDER_SCALE;
let padding = renderer.padding * RENDER_SCALE;
assert_eq!(img.height(), 2 * cell_h + padding * 2);
assert_ne!(
*img.get_pixel(padding + 2, padding + cell_h + cell_h / 2),
theme.background,
"the trailing styled row was trimmed away"
);
}
#[test]
fn chrome_and_bare_paths_trim_height_identically() {
let mut renderer = bare_renderer();
renderer.themes.insert("dark".to_string(), Theme::dark());
let theme = Theme::dark();
let captured = screen_of(b"one\r\ntwo", 24, 80);
let bare_chrome = ChromeOptions {
enabled: false,
preset: "none".to_string(),
title: None,
timestamp: false,
shadow: false,
radius: 0,
rounded: false,
outer_padding: 0,
title_bar_height: 0,
};
let framed = ChromeOptions {
enabled: true,
preset: "gnome".to_string(),
title: Some("demo".to_string()),
timestamp: false,
shadow: false,
radius: 0,
rounded: false,
outer_padding: 0,
title_bar_height: 34,
};
let render = |chrome: &ChromeOptions| {
renderer
.render_to_image(
&captured,
&theme,
&renderer.default_fonts,
chrome,
None,
true,
)
.unwrap()
};
let bare = render(&bare_chrome);
let with_chrome = render(&framed);
let cell_h = renderer.default_fonts.cell_height * RENDER_SCALE;
let padding = renderer.padding * RENDER_SCALE;
assert_eq!(bare.height(), 2 * cell_h + padding * 2);
assert_eq!(with_chrome.height(), bare.height() + 34 * RENDER_SCALE);
assert_eq!(with_chrome.width(), bare.width());
}
#[test]
fn long_titles_are_truncated_on_character_boundaries() {
let title = "é".repeat(MAX_TITLE_CHARS + 1);
let truncated = truncate_title(&title);
assert_eq!(truncated.chars().count(), MAX_TITLE_CHARS + 3);
assert!(truncated.ends_with("..."));
}
#[test]
fn round_image_corners_makes_corners_transparent_but_keeps_body() {
let renderer = bare_renderer();
let mut img = ImageBuffer::from_pixel(40, 40, Rgba([20, 20, 20, 255]));
renderer.round_image_corners(&mut img, 10);
assert_eq!(img.get_pixel(0, 0)[3], 0);
assert_eq!(img.get_pixel(39, 39)[3], 0);
assert_eq!(img.get_pixel(20, 0)[3], 255);
assert_eq!(img.get_pixel(0, 20)[3], 255);
assert_eq!(img.get_pixel(20, 20)[3], 255);
assert_eq!([img.get_pixel(0, 0)[0], img.get_pixel(0, 0)[1]], [20, 20]);
}
#[test]
fn round_image_corners_is_noop_for_zero_radius() {
let renderer = bare_renderer();
let mut img = ImageBuffer::from_pixel(20, 20, Rgba([10, 10, 10, 255]));
renderer.round_image_corners(&mut img, 0);
assert_eq!(img.get_pixel(0, 0)[3], 255);
}
#[test]
fn bare_render_rounds_corners_when_enabled_and_squares_when_disabled() {
let mut renderer = bare_renderer();
renderer.default_chrome.radius = 8;
let theme = Theme::dark();
let captured = screen_of(b"hello world", 3, 20);
let screen = &captured;
renderer.default_chrome.rounded = true;
let rounded = renderer
.render_to_image(
screen,
&theme,
&renderer.default_fonts,
&renderer.default_chrome,
None,
false,
)
.unwrap();
assert_eq!(rounded.get_pixel(0, 0)[3], 0, "rounded: corner transparent");
renderer.default_chrome.rounded = false;
let square = renderer
.render_to_image(
screen,
&theme,
&renderer.default_fonts,
&renderer.default_chrome,
None,
false,
)
.unwrap();
assert_eq!(square.get_pixel(0, 0)[3], 255, "square: corner opaque");
}
#[test]
fn chrome_options_default_rounded_is_true() {
let options = ChromeOptions::from_config(&ChromeConfig::default());
assert!(options.rounded);
}
#[test]
fn title_uses_fixed_monospace_cell_advance() {
let r = bare_renderer();
let size = 20.0;
let one_m = r.text_width(&r.default_fonts, "M", size);
assert!(one_m > 0);
assert_eq!(
r.text_width(&r.default_fonts, "MMMMMMMMMM", size),
one_m * 10
);
assert_eq!(
r.text_width(&r.default_fonts, "iiiiiiiiii", size),
one_m * 10
);
assert_eq!(r.text_width(&r.default_fonts, "Mi.lWx/9-", size), one_m * 9);
}
#[test]
fn chrome_text_sits_on_a_shared_baseline() {
let r = bare_renderer();
let size = 24.0;
let mut img: RgbaImage = ImageBuffer::from_pixel(400, 80, Rgba([0, 0, 0, 255]));
r.draw_text_at(
&mut img,
&r.default_fonts,
10,
40,
"oxy",
Rgba([255, 255, 255, 255]),
size,
);
let advance = r.text_width(&r.default_fonts, "M", size) as i32;
let bottom_of = |cell: i32| -> u32 {
let (x0, x1) = (10 + cell * advance, 10 + (cell + 1) * advance);
(0..img.height())
.rfind(|&y| {
(x0.max(0) as u32..(x1.max(0) as u32).min(img.width()))
.any(|x| img.get_pixel(x, y)[0] > 40)
})
.expect("glyph should have been drawn")
};
let (o, x, y) = (bottom_of(0), bottom_of(1), bottom_of(2));
assert!(
o.abs_diff(x) <= 1,
"flat and round glyphs must share a baseline: o={o}, x={x}"
);
assert!(
y > o + 1,
"descender must hang below the baseline: y={y}, o={o}"
);
}
#[test]
fn timestamp_is_right_aligned_on_the_same_baseline() {
let r = bare_renderer();
let size = 20.0;
let text = "2026-08-26 01:38:03 UTC";
let right_x = 380u32;
let mut img: RgbaImage = ImageBuffer::from_pixel(400, 60, Rgba([0, 0, 0, 255]));
r.draw_text_right_aligned(
&mut img,
&r.default_fonts,
right_x,
30,
text,
Rgba([255, 255, 255, 255]),
size,
);
let advance = r.text_width(&r.default_fonts, "M", size);
let start_x = right_x - r.text_width(&r.default_fonts, text, size);
let mut extents: Vec<(usize, u32, u32)> = Vec::new();
for (cell, _) in text.chars().enumerate().filter(|(_, c)| *c != ' ') {
let x0 = start_x + cell as u32 * advance;
let x1 = (x0 + advance).min(img.width());
let rows: Vec<u32> = (0..img.height())
.filter(|&y| (x0..x1).any(|x| img.get_pixel(x, y)[0] > 40))
.collect();
assert!(!rows.is_empty(), "cell {cell} was not drawn");
extents.push((cell, rows[0], *rows.last().unwrap()));
}
let tallest = extents.iter().map(|(_, t, b)| b - t).max().unwrap();
let full: Vec<u32> = extents
.iter()
.filter(|(_, t, b)| b - t >= tallest - 1)
.map(|(_, _, b)| *b)
.collect();
let (lo, hi) = (*full.iter().min().unwrap(), *full.iter().max().unwrap());
assert!(
hi - lo <= 1,
"timestamp glyphs drifted off the baseline: {lo} vs {hi}"
);
let hyphen = extents
.iter()
.find(|(cell, _, _)| text.chars().nth(*cell) == Some('-'))
.expect("hyphen cell");
assert!(
hyphen.2 < lo,
"a hyphen must not reach the baseline: {} vs {lo}",
hyphen.2
);
let inked: Vec<u32> = (0..img.width())
.filter(|&x| (0..img.height()).any(|y| img.get_pixel(x, y)[0] > 40))
.collect();
assert!(*inked.last().unwrap() < right_x);
assert!(right_x - *inked.last().unwrap() <= advance);
assert!(inked[0] >= start_x);
}
#[test]
fn sample_background_prefers_opaque_pane_color() {
let mut img = ImageBuffer::from_pixel(20, 20, Rgba([12, 34, 56, 255]));
img.put_pixel(0, 0, Rgba([0, 0, 0, 0]));
assert_eq!(
sample_background(&img, Rgba([9, 9, 9, 255])),
Rgba([12, 34, 56, 255])
);
let clear = ImageBuffer::from_pixel(20, 20, Rgba([0, 0, 0, 0]));
assert_eq!(
sample_background(&clear, Rgba([9, 9, 9, 255])),
Rgba([9, 9, 9, 255])
);
}
#[test]
fn normalize_newlines_converts_bare_lf_and_is_idempotent() {
use std::borrow::Cow;
assert_eq!(
normalize_newlines(b"a\nb\n").as_ref(),
b"a\r\nb\r\n".as_slice()
);
assert!(matches!(
normalize_newlines(b"a\r\nb\r\n"),
Cow::Borrowed(_)
));
assert!(matches!(
normalize_newlines(b"no newline"),
Cow::Borrowed(_)
));
assert_eq!(normalize_newlines(b"\nx").as_ref(), b"\r\nx".as_slice());
}
fn test_fonts() -> ThemeFonts {
ThemeFonts {
font: Font::from_bytes(
std::fs::read("fonts/JetBrainsMono-Regular.ttf").expect("font present"),
FontSettings::default(),
)
.expect("font parse"),
font_bold: None,
fallback_fonts: Vec::new(),
cell_width: 8,
cell_height: 16,
shaping: ShapingEngine::new(
vec![FontSource::Embedded(EMBEDDED_FONT)],
ShapingOptions::deterministic(),
),
}
}
fn renderer_with_chrome(default_chrome: ChromeOptions) -> Renderer {
Renderer {
theme_fonts: HashMap::new(),
default_fonts: Arc::new(test_fonts()),
font_size: 16.0,
themes: HashMap::new(),
default_theme: "dark".to_string(),
default_chrome,
padding: 16,
max_scrollback_lines: crate::capture::DEFAULT_MAX_SCROLLBACK_LINES,
}
}
fn bare_renderer() -> Renderer {
renderer_with_chrome(ChromeOptions {
enabled: false,
preset: "none".to_string(),
title: None,
timestamp: false,
shadow: false,
radius: 0,
rounded: true,
outer_padding: 0,
title_bar_height: 0,
})
}
fn renderer_with_measured_cells() -> Renderer {
let fonts = ThemeFonts::load(
&FontChainSpec {
primary: None,
bold: None,
fallbacks: Vec::new(),
},
16.0,
&ShapingOptions::deterministic(),
)
.expect("the embedded font loads");
let mut renderer = bare_renderer();
renderer.default_fonts = Arc::new(fonts);
renderer
}
#[test]
fn width_trim_leaves_the_same_padding_on_both_sides() {
let renderer = bare_renderer();
let theme = Theme::dark();
let cols = 120u16;
let used = 110usize;
let captured = screen_of("x".repeat(used).as_bytes(), 4, cols);
let screen = &captured;
let img = renderer
.render_screen(screen, &theme, &renderer.default_fonts, None, true)
.unwrap();
let cell_w = renderer.default_fonts.cell_width * RENDER_SCALE;
let padding = renderer.padding * RENDER_SCALE;
assert_eq!(img.width(), used as u32 * cell_w + padding * 2);
assert!(
ink_in_columns(
&img,
padding + (used as u32 - 1) * cell_w,
padding + used as u32 * cell_w
) > 0,
"the last column of text was trimmed away"
);
let bg = theme.background;
let inked = |x: u32| (0..img.height()).any(|y| *img.get_pixel(x, y) != bg);
let left = (0..img.width()).find(|&x| inked(x)).expect("ink");
let right = (0..img.width()).rev().find(|&x| inked(x)).expect("ink");
let right_margin = img.width() - 1 - right;
assert!(
right_margin >= 1,
"anti-aliased glyph edge touches the right border"
);
assert!(
(left as i32 - right_margin as i32).unsigned_abs() <= cell_w,
"asymmetric margins: {left}px on the left, {right_margin}px on the right"
);
}
#[test]
fn width_trim_keeps_trailing_styled_cells() {
let renderer = bare_renderer();
let theme = Theme::dark();
let captured = screen_of(b"hi\x1b[42m \x1b[0m", 4, 80);
let img = renderer
.render_screen(&captured, &theme, &renderer.default_fonts, None, true)
.unwrap();
let cell_w = renderer.default_fonts.cell_width * RENDER_SCALE;
let padding = renderer.padding * RENDER_SCALE;
assert_eq!(img.width(), 6 * cell_w + padding * 2);
assert_ne!(
*img.get_pixel(padding + 5 * cell_w + cell_w / 2, padding + 2),
theme.background,
"the trailing styled cell was trimmed away"
);
}
#[test]
fn width_trim_keeps_a_wide_characters_continuation_cell() {
let renderer = bare_renderer();
let theme = Theme::dark();
let captured = screen_of("ab\u{4f60}".as_bytes(), 4, 80);
let img = renderer
.render_screen(&captured, &theme, &renderer.default_fonts, None, true)
.unwrap();
let cell_w = renderer.default_fonts.cell_width * RENDER_SCALE;
let padding = renderer.padding * RENDER_SCALE;
assert_eq!(img.width(), 4 * cell_w + padding * 2);
}
#[test]
fn width_trim_can_be_disabled() {
let renderer = bare_renderer();
let theme = Theme::dark();
let captured = screen_of(b"hi", 4, 80);
let img = renderer
.render_screen(&captured, &theme, &renderer.default_fonts, None, false)
.unwrap();
let cell_w = renderer.default_fonts.cell_width * RENDER_SCALE;
let padding = renderer.padding * RENDER_SCALE;
assert_eq!(img.width(), 80 * cell_w + padding * 2);
}
#[test]
fn redaction_masks_sensitive_cells_in_rendered_image() {
use crate::redaction::{RedactionConfig, RedactionEngine};
let renderer = bare_renderer();
let theme = Theme::dark();
let engine = RedactionEngine::from_config(&RedactionConfig::default()).unwrap();
let captured = screen_of(b"ip 10.20.30.40 up", 3, 40);
let screen = &captured;
let map = engine.redact_screen(screen, None);
assert!(!map.is_empty(), "expected the IPv4 address to be redacted");
let redacted = renderer
.render_screen(screen, &theme, &renderer.default_fonts, Some(&map), true)
.unwrap();
let plain = renderer
.render_screen(screen, &theme, &renderer.default_fonts, None, true)
.unwrap();
let scale = 2u32;
let cell_w = renderer.default_fonts.cell_width * scale;
let cell_h = renderer.default_fonts.cell_height * scale;
let padding = renderer.padding * scale;
let px = 10 * cell_w + padding + cell_w / 2;
let py = padding + cell_h / 2;
assert_eq!(
*redacted.get_pixel(px, py),
REDACT_BG,
"redacted cell should be painted red"
);
assert_ne!(
*plain.get_pixel(px, py),
REDACT_BG,
"un-redacted render should not contain redaction red"
);
}
#[test]
fn render_bytes_scrubs_plain_text_and_reports_audit() {
use crate::redaction::{RedactionConfig, RedactionEngine};
let mut renderer = bare_renderer();
renderer.themes.insert("dark".to_string(), Theme::dark());
let engine = RedactionEngine::from_config(&RedactionConfig::default()).unwrap();
let request = RedactionRequest {
engine: &engine,
rules: None,
};
let out_dir = std::path::Path::new("target/redaction-test-out");
std::fs::create_dir_all(out_dir).unwrap();
let secret = b"host 203.0.113.55 admin@example.com\n";
let (path, plain_text, audit, _meta) = renderer
.render_bytes(
secret,
40,
3,
out_dir,
Some("redaction test"),
Some("dark"),
None,
Some(&request),
TextOptions {
strip_ansi: false,
redact_text: true,
embed_description: true,
from_screen: false,
},
true,
)
.unwrap();
assert!(!plain_text.contains("203.0.113.55"));
assert!(!plain_text.contains("admin@example.com"));
assert!(plain_text.contains('\u{2588}'));
let img = image::open(&path).unwrap().to_rgba8();
let has_red = img.pixels().any(|p| *p == REDACT_BG);
assert!(has_red, "rendered PNG should contain redaction blocks");
assert!(audit.iter().any(|(name, _)| name == "ipv4"));
assert!(audit.iter().any(|(name, _)| name == "email"));
std::fs::remove_file(&path).ok();
}
#[test]
fn render_bytes_default_keeps_original_text_but_redacts_image() {
use crate::redaction::{RedactionConfig, RedactionEngine};
let mut renderer = bare_renderer();
renderer.themes.insert("dark".to_string(), Theme::dark());
let engine = RedactionEngine::from_config(&RedactionConfig::default()).unwrap();
let request = RedactionRequest {
engine: &engine,
rules: None,
};
let out_dir = std::path::Path::new("target/redaction-default-out");
std::fs::create_dir_all(out_dir).unwrap();
let secret = b"host 203.0.113.55 here\n";
let (path, plain_text, audit, _meta) = renderer
.render_bytes(
secret,
40,
3,
out_dir,
Some("default redaction test"),
Some("dark"),
None,
Some(&request),
TextOptions::default(),
true,
)
.unwrap();
assert!(
plain_text.contains("203.0.113.55"),
"default text should keep original value: {}",
plain_text
);
assert!(!plain_text.contains('\u{2588}'));
assert!(audit.iter().any(|(name, _)| name == "ipv4"));
let img = image::open(&path).unwrap().to_rgba8();
assert!(img.pixels().any(|p| *p == REDACT_BG));
std::fs::remove_file(&path).ok();
}
fn png_description(path: &std::path::Path) -> Option<String> {
let file = std::io::BufReader::new(std::fs::File::open(path).unwrap());
let decoder = png::Decoder::new(file);
let mut reader = decoder.read_info().unwrap();
let mut buf = vec![0; reader.output_buffer_size().unwrap()];
reader.next_frame(&mut buf).unwrap();
reader
.info()
.utf8_text
.iter()
.find(|chunk| chunk.keyword == "Description")
.map(|chunk| chunk.get_text().expect("iTXt text should decode"))
}
#[test]
fn png_embeds_terminal_text_as_description() {
let mut renderer = bare_renderer();
renderer.themes.insert("dark".to_string(), Theme::dark());
let out_dir = std::path::Path::new("target/description-test-out");
std::fs::create_dir_all(out_dir).unwrap();
let (path, _text, _audit, _meta) = renderer
.render_bytes(
b"hello accessible world\n",
40,
3,
out_dir,
Some("description on"),
Some("dark"),
None,
None,
TextOptions {
embed_description: true,
..TextOptions::default()
},
true,
)
.unwrap();
let description = png_description(&path).expect("Description chunk missing");
assert!(
description.contains("hello accessible world"),
"unexpected description: {:?}",
description
);
std::fs::remove_file(&path).ok();
let (path, _text, _audit, _meta) = renderer
.render_bytes(
b"hello accessible world\n",
40,
3,
out_dir,
Some("description off"),
Some("dark"),
None,
None,
TextOptions::default(),
true,
)
.unwrap();
assert_eq!(png_description(&path), None);
std::fs::remove_file(&path).ok();
}
#[test]
fn embedded_description_is_redacted() {
use crate::redaction::{RedactionConfig, RedactionEngine};
let mut renderer = bare_renderer();
renderer.themes.insert("dark".to_string(), Theme::dark());
let engine = RedactionEngine::from_config(&RedactionConfig::default()).unwrap();
let request = RedactionRequest {
engine: &engine,
rules: None,
};
let out_dir = std::path::Path::new("target/description-test-out");
std::fs::create_dir_all(out_dir).unwrap();
let (path, _text, _audit, _meta) = renderer
.render_bytes(
b"key AKIAIOSFODNN7EXAMPLE end\n",
60,
3,
out_dir,
Some("description redacted"),
Some("dark"),
None,
Some(&request),
TextOptions {
embed_description: true,
..TextOptions::default()
},
true,
)
.unwrap();
let description = png_description(&path).expect("Description chunk missing");
assert!(
!description.contains("AKIAIOSFODNN7EXAMPLE"),
"description leaked a redacted secret: {:?}",
description
);
assert!(description.contains("key "));
assert!(
description.contains("\u{2588}\u{2588}\u{2588}\u{2588}"),
"got: {:?}",
description
);
std::fs::remove_file(&path).ok();
}
#[test]
fn embedded_description_preserves_unicode() {
let mut renderer = bare_renderer();
renderer.themes.insert("dark".to_string(), Theme::dark());
let out_dir = std::path::Path::new("target/description-test-out");
std::fs::create_dir_all(out_dir).unwrap();
let unicode = "\u{2500} \u{2502} \u{250c} \u{2713} \u{3bb} \u{6f22}";
let source = format!("{}\n", unicode);
let (path, _text, _audit, _meta) = renderer
.render_bytes(
source.as_bytes(),
40,
3,
out_dir,
Some("description unicode"),
Some("dark"),
None,
None,
TextOptions {
embed_description: true,
..TextOptions::default()
},
true,
)
.unwrap();
let description = png_description(&path).expect("Description chunk missing");
assert!(
description.contains(unicode),
"unicode did not round-trip: {:?}",
description
);
assert!(
!description.contains('?') && !description.contains('\u{fffd}'),
"unicode was transliterated or replaced: {:?}",
description
);
std::fs::remove_file(&path).ok();
}
#[test]
fn description_text_chunk_sanitizes_and_truncates_on_char_boundary() {
assert_eq!(description_text_chunk("a\u{7}b\u{1b}c\nd\n\n"), "abc\nd");
let long = "\u{6f22}".repeat(MAX_DESCRIPTION_BYTES);
let capped = description_text_chunk(&long);
assert!(capped.len() <= MAX_DESCRIPTION_BYTES);
assert!(capped.chars().all(|c| c == '\u{6f22}'));
assert_eq!(capped.len() % '\u{6f22}'.len_utf8(), 0);
}
#[test]
fn parse_hex_color_rejects_non_ascii_input() {
assert!(parse_hex_color("#abc\u{20ac}").is_err());
assert!(parse_hex_color("#zzzzzz").is_err());
assert_eq!(parse_hex_color("#1e1e1e").unwrap(), Rgba([30, 30, 30, 255]));
}
#[test]
fn sanitize_base_name_derives_readable_slugs() {
assert_eq!(sanitize_base_name("ls -la"), "ls-la");
assert_eq!(sanitize_base_name("whoami uname -a"), "whoami-uname-a");
assert_eq!(sanitize_base_name(" git status!! "), "git-status");
assert_eq!(sanitize_base_name("///"), "screenshot");
assert_eq!(sanitize_base_name(""), "screenshot");
let long = "a ".repeat(80);
let slug = sanitize_base_name(&long);
assert!(slug.chars().count() <= 60);
assert!(!slug.ends_with('-'));
}
#[test]
fn fallback_output_name_combines_cwd_and_first_word() {
use std::path::Path;
assert_eq!(
fallback_output_name(Some(Path::new("/home/adam/Desktop/nrs")), "cargo test"),
"nrs cargo"
);
assert_eq!(
fallback_output_name(Some(Path::new("/home/adam/Desktop/nrs/src")), "ls -la"),
"src ls"
);
assert_eq!(fallback_output_name(None, "git log --oneline"), "git");
assert_eq!(
fallback_output_name(Some(Path::new("/tmp/work")), ""),
"work"
);
assert_eq!(fallback_output_name(None, ""), "");
}
#[test]
fn unique_png_path_appends_numeric_suffixes() {
let dir = std::path::Path::new("target/unique-name-test");
std::fs::create_dir_all(dir).unwrap();
for name in ["cmd.png", "cmd-2.png", "cmd-3.png"] {
std::fs::remove_file(dir.join(name)).ok();
}
let first = unique_png_path(dir, "cmd");
assert_eq!(first, dir.join("cmd.png"));
std::fs::write(&first, b"x").unwrap();
let second = unique_png_path(dir, "cmd");
assert_eq!(second, dir.join("cmd-2.png"));
std::fs::write(&second, b"x").unwrap();
let third = unique_png_path(dir, "cmd");
assert_eq!(third, dir.join("cmd-3.png"));
for name in ["cmd.png", "cmd-2.png", "cmd-3.png"] {
std::fs::remove_file(dir.join(name)).ok();
}
}
const LIMITED_PRIMARY: &str = "tests/fixtures/limited-ascii.ttf";
const CJK_FALLBACK: &str = "tests/fixtures/cjk-fallback.ttf";
const FALLBACK_CHARS: [char; 5] = ['\u{2500}', '\u{2502}', '\u{250c}', '\u{2713}', '\u{3bb}'];
fn renderer_with(primary: Option<&str>, fallbacks: &[&str]) -> Renderer {
renderer_with_shaping(primary, fallbacks, ShapingOptions::deterministic())
}
fn renderer_with_shaping(
primary: Option<&str>,
fallbacks: &[&str],
shaping: ShapingOptions,
) -> Renderer {
let fallbacks: Vec<PathBuf> = fallbacks.iter().map(PathBuf::from).collect();
Renderer::new_with_shaping(
&FontSelection {
font_override: primary.map(PathBuf::from),
font_bold_override: None,
global_font: None,
global_fallback_fonts: fallbacks,
},
16.0,
&HashMap::new(),
"dark",
&ChromeConfig::default(),
RendererOptions::default(),
shaping,
)
.expect("renderer builds")
}
fn render_line(renderer: &Renderer, text: &str, cols: u16) -> RgbaImage {
let captured = screen_of(text.as_bytes(), 2, cols);
renderer
.render_screen(
&captured,
&Theme::dark(),
&renderer.default_fonts,
None,
false,
)
.expect("render")
}
fn ink(img: &RgbaImage) -> usize {
let bg = Theme::dark().background;
img.pixels().filter(|p| **p != bg).count()
}
fn ink_in_columns(img: &RgbaImage, x0: u32, x1: u32) -> usize {
let bg = Theme::dark().background;
let mut count = 0;
for y in 0..img.height() {
for x in x0..x1.min(img.width()) {
if *img.get_pixel(x, y) != bg {
count += 1;
}
}
}
count
}
#[test]
fn missing_box_drawing_glyphs_fall_back_to_the_embedded_font() {
let renderer = renderer_with(Some(LIMITED_PRIMARY), &[]);
for ch in FALLBACK_CHARS {
assert!(
!font_covers(&renderer.default_fonts.font, ch, 32.0),
"fixture primary font unexpectedly covers {:?}",
ch
);
let chosen = renderer.font_for_char(&renderer.default_fonts, ch, false, 32.0);
assert!(chosen.is_fallback, "{:?} did not use a fallback font", ch);
assert!(
font_covers(chosen.font, ch, 32.0),
"fallback font chosen for {:?} does not cover it",
ch
);
}
let chosen = renderer.font_for_char(&renderer.default_fonts, 'M', false, 32.0);
assert!(!chosen.is_fallback, "ASCII must stay on the primary font");
}
#[test]
fn embedded_font_is_always_the_first_fallback() {
let renderer = renderer_with(Some(LIMITED_PRIMARY), &[CJK_FALLBACK]);
assert_eq!(
renderer.default_fonts.fallback_fonts.len(),
2,
"expected the embedded font plus one configured fallback"
);
let embedded = &renderer.default_fonts.fallback_fonts[0];
for ch in FALLBACK_CHARS {
assert!(
font_covers(embedded, ch, 32.0),
"embedded JetBrains Mono should cover {:?}",
ch
);
let chosen = renderer.font_for_char(&renderer.default_fonts, ch, false, 32.0);
assert!(
std::ptr::eq(chosen.font, embedded),
"{:?} skipped the embedded font",
ch
);
}
}
#[test]
fn embedded_font_renders_box_drawing_and_symbols() {
let renderer = renderer_with(Some(LIMITED_PRIMARY), &[]);
let embedded = &renderer.default_fonts.fallback_fonts[0];
for ch in FALLBACK_CHARS {
let (metrics, bitmap) = embedded.rasterize(ch, 32.0);
assert!(
!bitmap.is_empty() && metrics.width > 0 && metrics.height > 0,
"embedded font produced no bitmap for {:?}",
ch
);
}
let drawn: String = FALLBACK_CHARS.iter().collect();
let img = render_line(&renderer, &drawn, 10);
assert!(ink(&img) > 0, "fallback glyphs left no ink on the canvas");
}
#[test]
fn uncovered_cjk_stays_missing_without_a_configured_fallback() {
let renderer = renderer_with(Some(LIMITED_PRIMARY), &[]);
let chosen = renderer.font_for_char(&renderer.default_fonts, '\u{4e2d}', false, 32.0);
assert!(
!chosen.is_fallback,
"no fallback should cover this CJK char"
);
assert!(!font_covers(chosen.font, '\u{4e2d}', 32.0));
assert_eq!(
ink(&render_line(&renderer, "\u{4e2d}", 10)),
0,
"a character no font covers must not draw a substitute glyph"
);
}
#[test]
fn configured_fallback_font_is_loaded_and_selected() {
let renderer = renderer_with(Some(LIMITED_PRIMARY), &[CJK_FALLBACK]);
let chosen = renderer.font_for_char(&renderer.default_fonts, '\u{4e2d}', false, 32.0);
assert!(chosen.is_fallback, "configured fallback was not selected");
assert!(std::ptr::eq(
chosen.font,
&renderer.default_fonts.fallback_fonts[1]
));
assert!(
ink(&render_line(&renderer, "\u{4e2d}", 10)) > 0,
"configured fallback glyph was not drawn"
);
}
#[test]
fn broken_fallback_fonts_warn_and_are_skipped() {
let dir = Path::new("target/font-fallback-test");
std::fs::create_dir_all(dir).unwrap();
let junk = dir.join("not-a-font.ttf");
std::fs::write(&junk, b"this is definitely not a font").unwrap();
let renderer = renderer_with(
Some(LIMITED_PRIMARY),
&[
"target/font-fallback-test/missing-font.ttf",
junk.to_str().unwrap(),
CJK_FALLBACK,
],
);
assert_eq!(renderer.default_fonts.fallback_fonts.len(), 2);
assert!(
renderer
.font_for_char(&renderer.default_fonts, '\u{2500}', false, 32.0)
.is_fallback
);
assert!(
renderer
.font_for_char(&renderer.default_fonts, '\u{4e2d}', false, 32.0)
.is_fallback
);
}
#[test]
fn fallback_glyphs_keep_the_primary_cell_metrics() {
let plain = renderer_with(Some(LIMITED_PRIMARY), &[]);
let with_fallbacks = renderer_with(Some(LIMITED_PRIMARY), &[CJK_FALLBACK]);
assert_eq!(
plain.default_fonts.cell_width,
with_fallbacks.default_fonts.cell_width
);
assert_eq!(
plain.default_fonts.cell_height,
with_fallbacks.default_fonts.cell_height
);
let cols = 4;
let img = render_line(&with_fallbacks, "\u{2500}", cols);
let expected_width = cols as u32 * plain.default_fonts.cell_width * RENDER_SCALE
+ plain.padding * RENDER_SCALE * 2;
assert_eq!(
img.width(),
expected_width,
"fallback changed the grid width"
);
let cell_w = plain.default_fonts.cell_width * RENDER_SCALE;
let padding = plain.padding * RENDER_SCALE;
assert!(ink_in_columns(&img, padding, padding + cell_w) > 0);
assert_eq!(
ink_in_columns(&img, padding + cell_w + cell_w / 2, img.width()),
0,
"fallback glyph spilled into the next cell"
);
}
#[test]
fn fallback_glyphs_sit_cleanly_in_the_cell() {
let direct = renderer_with(None, &[]);
let via_fallback = renderer_with(Some(LIMITED_PRIMARY), &[]);
let bbox = |img: &RgbaImage| -> (u32, u32, u32, u32) {
let bg = Theme::dark().background;
let (mut x0, mut y0, mut x1, mut y1) = (u32::MAX, u32::MAX, 0, 0);
for (x, y, p) in img.enumerate_pixels() {
if *p != bg {
x0 = x0.min(x);
y0 = y0.min(y);
x1 = x1.max(x);
y1 = y1.max(y);
}
}
(x0, y0, x1, y1)
};
let measure = |r: &Renderer| {
let img = render_line(r, "\u{2500}", 4);
let padding = r.padding * RENDER_SCALE;
let cell_w = r.default_fonts.cell_width * RENDER_SCALE;
let (x0, y0, x1, y1) = bbox(&img);
(
x0 as i64 - padding as i64,
(padding + cell_w) as i64 - (x1 + 1) as i64,
((y0 + y1) / 2) as i64 - padding as i64,
)
};
let (direct_left, direct_right, direct_mid) = measure(&direct);
let (fb_left, fb_right, fb_mid) = measure(&via_fallback);
assert!(
fb_left <= direct_left + 1 && fb_right <= direct_right + 1,
"fallback rule does not reach its cell edges (insets {}/{} vs {}/{})",
fb_left,
fb_right,
direct_left,
direct_right
);
assert!(
fb_mid.abs_diff(direct_mid) <= 2,
"fallback glyph sits at a different height: {} vs {}",
fb_mid,
direct_mid
);
}
#[test]
fn wide_fallback_glyphs_respect_continuation_cells() {
let renderer = renderer_with(Some(LIMITED_PRIMARY), &[CJK_FALLBACK]);
let cols = 6;
let img = render_line(&renderer, "\u{4e2d}", cols);
let cell_w = renderer.default_fonts.cell_width * RENDER_SCALE;
let padding = renderer.padding * RENDER_SCALE;
assert!(
ink_in_columns(&img, padding, padding + cell_w * 2) > 0,
"wide glyph drew nothing in its two cells"
);
assert_eq!(
ink_in_columns(&img, padding + cell_w * 2, img.width()),
0,
"wide glyph spilled past its continuation cell"
);
}
#[test]
fn fallback_box_drawing_tiles_without_gaps() {
let renderer = renderer_with(Some(LIMITED_PRIMARY), &[]);
let cols = 6;
let img = render_line(&renderer, &"\u{2500}".repeat(4), cols);
let bg = Theme::dark().background;
let padding = renderer.padding * RENDER_SCALE;
let run_end = padding + renderer.default_fonts.cell_width * RENDER_SCALE * 4;
let row = (0..img.height())
.max_by_key(|y| {
(0..img.width())
.filter(|x| *img.get_pixel(*x, *y) != bg)
.count()
})
.expect("image has rows");
let gaps: Vec<u32> = (padding..run_end)
.filter(|x| *img.get_pixel(*x, row) == bg)
.collect();
assert!(
gaps.is_empty(),
"horizontal rule from the fallback font has gaps at columns {:?}",
gaps
);
}
#[test]
fn fallback_box_corners_keep_their_side_bearings() {
let renderer = renderer_with(Some(LIMITED_PRIMARY), &[]);
let img = render_line(&renderer, "\u{250c}", 4);
let cell_w = renderer.default_fonts.cell_width * RENDER_SCALE;
let padding = renderer.padding * RENDER_SCALE;
let mid = padding + cell_w / 2;
let left = ink_in_columns(&img, padding, mid);
let right = ink_in_columns(&img, mid, padding + cell_w);
assert!(
right > left,
"'┌' should ink mostly the right half of its cell (left {} vs right {})",
left,
right
);
}
fn theme_config_with_fonts(font: Option<&str>, fallbacks: &[&str]) -> ThemeConfig {
ThemeConfig {
foreground: "#ffffff".to_string(),
background: "#000000".to_string(),
font: font.map(str::to_string),
font_bold: None,
fallback_fonts: fallbacks.iter().map(|f| f.to_string()).collect(),
palette: std::array::from_fn(|_| "#808080".to_string()),
base_dir: None,
}
}
#[test]
fn each_theme_gets_its_own_font_chain() {
let mut themes = HashMap::new();
themes.insert(
"ascii-only".to_string(),
theme_config_with_fonts(Some(LIMITED_PRIMARY), &[]),
);
themes.insert(
"cjk".to_string(),
theme_config_with_fonts(Some(LIMITED_PRIMARY), &[CJK_FALLBACK]),
);
themes.insert("embedded".to_string(), theme_config_with_fonts(None, &[]));
themes.insert(
"embedded-too".to_string(),
theme_config_with_fonts(None, &[]),
);
let renderer = Renderer::new(
&FontSelection::default(),
16.0,
&themes,
"embedded",
&ChromeConfig::default(),
)
.expect("renderer builds");
let cjk_fonts = renderer.fonts_for(Some("cjk"));
assert!(
renderer
.font_for_char(cjk_fonts, '\u{4e2d}', false, 32.0)
.is_fallback
);
let ascii_fonts = renderer.fonts_for(Some("ascii-only"));
assert!(
!renderer
.font_for_char(ascii_fonts, '\u{4e2d}', false, 32.0)
.is_fallback
);
let embedded_fonts = renderer.fonts_for(Some("embedded"));
assert!(ascii_fonts.cell_width > embedded_fonts.cell_width);
assert!(std::ptr::eq(
renderer.fonts_for(Some("embedded-too")),
embedded_fonts
));
assert!(std::ptr::eq(
renderer.fonts_for(Some("nope")),
embedded_fonts
));
assert!(std::ptr::eq(renderer.fonts_for(None), embedded_fonts));
}
#[test]
fn font_override_applies_to_every_theme() {
let mut themes = HashMap::new();
themes.insert("embedded".to_string(), theme_config_with_fonts(None, &[]));
themes.insert(
"ascii-only".to_string(),
theme_config_with_fonts(Some(LIMITED_PRIMARY), &[]),
);
let renderer = Renderer::new(
&FontSelection {
font_override: Some(PathBuf::from(LIMITED_PRIMARY)),
..FontSelection::default()
},
16.0,
&themes,
"embedded",
&ChromeConfig::default(),
)
.expect("renderer builds");
let overridden = renderer.fonts_for(Some("embedded"));
let declared = renderer.fonts_for(Some("ascii-only"));
assert_eq!(overridden.cell_width, declared.cell_width);
assert!(std::ptr::eq(overridden, declared));
}
#[test]
fn compose_pads_narrow_panes_instead_of_rescaling_them() {
let dir = std::path::Path::new("target/compose-padding-test");
std::fs::create_dir_all(dir).unwrap();
let wide_path = dir.join("wide.png");
let narrow_path = dir.join("narrow.png");
let wide: RgbaImage = ImageBuffer::from_pixel(40, 10, Rgba([10, 10, 10, 255]));
let mut narrow: RgbaImage = ImageBuffer::from_pixel(20, 10, Rgba([80, 20, 20, 255]));
narrow.put_pixel(5, 5, Rgba([255, 255, 0, 255]));
save_png(&wide, &wide_path, None).unwrap();
save_png(&narrow, &narrow_path, None).unwrap();
let composed = compose_images(
&[wide_path, narrow_path],
ComposeLayout::Vertical,
0,
Rgba([0, 0, 0, 255]),
)
.expect("compose");
assert_eq!(composed.dimensions(), (40, 20));
assert_eq!(*composed.get_pixel(5, 15), Rgba([255, 255, 0, 255]));
assert_eq!(*composed.get_pixel(6, 15), Rgba([80, 20, 20, 255]));
assert_eq!(*composed.get_pixel(30, 15), Rgba([80, 20, 20, 255]));
}
#[test]
fn composed_description_joins_panes_and_keeps_unicode() {
let dir = std::path::Path::new("target/composed-description-test");
std::fs::create_dir_all(dir).unwrap();
let img: RgbaImage = ImageBuffer::from_pixel(4, 4, Rgba([0, 0, 0, 255]));
let first = dir.join("first.png");
let second = dir.join("second.png");
let bare = dir.join("bare.png");
save_png(&img, &first, Some("héllo ✓ \u{4e2d}\u{6587}")).unwrap();
save_png(&img, &second, Some("λ ─┐ second")).unwrap();
save_png(&img, &bare, None).unwrap();
assert_eq!(
read_png_description(&first).as_deref(),
Some("héllo ✓ \u{4e2d}\u{6587}")
);
assert_eq!(read_png_description(&bare), None);
let joined = composed_description(&[first.clone(), second.clone()])
.expect("panes have descriptions");
assert_eq!(
joined,
"héllo ✓ \u{4e2d}\u{6587}\n\n--- Pane 2 ---\n\nλ ─┐ second"
);
let mixed =
composed_description(&[bare.clone(), second]).expect("one pane has a description");
assert!(mixed.starts_with("(no description)"));
assert!(mixed.contains("--- Pane 2 ---"));
assert_eq!(composed_description(&[bare.clone(), bare]), None);
}
const CHROME_PRESETS: [&str; 4] = ["minimal", "gnome", "macos", "report"];
fn preset_chrome(preset: &str, rounded: bool, shadow: bool) -> ChromeOptions {
ChromeOptions {
enabled: true,
preset: preset.to_string(),
title: Some("demo".to_string()),
timestamp: false,
shadow,
radius: 14,
rounded,
outer_padding: 18,
title_bar_height: 34,
}
}
fn framed(preset: &str, rounded: bool, shadow: bool) -> RgbaImage {
let renderer = bare_renderer();
let theme = Theme::dark();
let terminal = ImageBuffer::from_pixel(400, 80, theme.background);
renderer.compose_with_chrome(
terminal,
&theme,
&renderer.default_fonts,
&preset_chrome(preset, rounded, shadow),
)
}
fn rounded_rect_distance(x: u32, y: u32, w: u32, h: u32, r: f32) -> f32 {
let (px, py) = (x as f32 + 0.5, y as f32 + 0.5);
let (hw, hh) = (w as f32 / 2.0, h as f32 / 2.0);
let qx = (px - hw).abs() - (hw - r);
let qy = (py - hh).abs() - (hh - r);
(qx.max(0.0).powi(2) + qy.max(0.0).powi(2)).sqrt() + qx.max(qy).min(0.0) - r
}
#[test]
fn every_chrome_preset_has_transparent_outer_corners() {
for preset in CHROME_PRESETS {
let img = framed(preset, true, false);
let (w, h) = img.dimensions();
for (x, y) in [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)] {
assert_eq!(
img.get_pixel(x, y)[3],
0,
"{preset}: corner ({x}, {y}) is not transparent"
);
}
let partial = img.pixels().filter(|p| p[3] > 0 && p[3] < 255).count();
assert!(
partial > 0,
"{preset}: rounded corners have no anti-aliased pixels"
);
}
}
#[test]
fn no_opaque_pixels_outside_the_rounded_frame() {
let radius = (14 * RENDER_SCALE) as f32;
for preset in CHROME_PRESETS {
let img = framed(preset, true, false);
let (w, h) = img.dimensions();
for y in 0..h {
for x in 0..w {
let alpha = img.get_pixel(x, y)[3];
if rounded_rect_distance(x, y, w, h, radius) > 0.75 {
assert_eq!(
alpha, 0,
"{preset}: pixel ({x}, {y}) outside the frame is not transparent"
);
}
}
}
}
}
#[test]
fn shadow_outside_the_frame_is_never_opaque() {
let radius = (14 * RENDER_SCALE) as f32;
for preset in CHROME_PRESETS {
let img = framed(preset, true, true);
let (w, h) = img.dimensions();
let offset = 16 * RENDER_SCALE / 2;
let (frame_w, frame_h) = (w - offset * 2, h - offset * 2);
let mut shadow_pixels = 0usize;
for y in 0..h {
for x in 0..w {
let alpha = img.get_pixel(x, y)[3];
if alpha == 0 {
continue;
}
let (fx, fy) = (x as i64 - offset as i64, y as i64 - offset as i64);
let outside = fx < 0
|| fy < 0
|| fx >= frame_w as i64
|| fy >= frame_h as i64
|| rounded_rect_distance(fx as u32, fy as u32, frame_w, frame_h, radius)
> 0.75;
if outside {
shadow_pixels += 1;
assert!(
alpha < 255,
"{preset}: opaque pixel ({x}, {y}) outside the frame"
);
}
}
}
assert!(shadow_pixels > 0, "{preset}: shadow was not drawn");
}
}
#[test]
fn frame_padding_matches_the_terminal_background() {
let background = Theme::dark().background;
for preset in CHROME_PRESETS {
let img = framed(preset, true, false);
let (w, h) = img.dimensions();
for (x, y) in [(4, h / 2), (w / 2, h - 4)] {
assert_eq!(
*img.get_pixel(x, y),
background,
"{preset}: padding at ({x}, {y}) is not the terminal background"
);
}
}
}
#[test]
fn square_chrome_keeps_opaque_corners() {
for preset in CHROME_PRESETS {
let img = framed(preset, false, false);
let (w, h) = img.dimensions();
for (x, y) in [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)] {
assert_eq!(
img.get_pixel(x, y)[3],
255,
"{preset}: square corner ({x}, {y}) lost its opacity"
);
}
}
}
#[derive(Debug, PartialEq, Eq)]
struct MaskStats {
width: u32,
height: u32,
count: usize,
left: usize,
right: usize,
top: usize,
bottom: usize,
origin: (u32, u32),
}
fn mask_stats(img: &RgbaImage, color: Rgba<u8>) -> MaskStats {
let points: Vec<(u32, u32)> = img
.enumerate_pixels()
.filter(|(_, _, p)| **p == color)
.map(|(x, y, _)| (x, y))
.collect();
assert!(!points.is_empty(), "no pixels of {:?} were drawn", color);
let (x0, x1) = (
points.iter().map(|p| p.0).min().unwrap(),
points.iter().map(|p| p.0).max().unwrap(),
);
let (y0, y1) = (
points.iter().map(|p| p.1).min().unwrap(),
points.iter().map(|p| p.1).max().unwrap(),
);
let cx = (x0 + x1) as f32 / 2.0;
let cy = (y0 + y1) as f32 / 2.0;
MaskStats {
width: x1 - x0 + 1,
height: y1 - y0 + 1,
count: points.len(),
left: points.iter().filter(|p| (p.0 as f32) < cx).count(),
right: points.iter().filter(|p| (p.0 as f32) > cx).count(),
top: points.iter().filter(|p| (p.1 as f32) < cy).count(),
bottom: points.iter().filter(|p| (p.1 as f32) > cy).count(),
origin: (x0, y0),
}
}
#[test]
fn macos_traffic_lights_are_equal_symmetric_circles() {
let img = framed("macos", true, false);
let colors = [
Rgba([255, 95, 86, 255]),
Rgba([255, 189, 46, 255]),
Rgba([39, 201, 63, 255]),
];
let stats: Vec<MaskStats> = colors.iter().map(|c| mask_stats(&img, *c)).collect();
for (stat, color) in stats.iter().zip(colors) {
assert_eq!(
stat.width, stat.height,
"{color:?} button is not square (so not round)"
);
assert_eq!(
stat.left, stat.right,
"{color:?} button is not left/right symmetric"
);
assert_eq!(
stat.top, stat.bottom,
"{color:?} button is not top/bottom symmetric"
);
}
for other in &stats[1..] {
assert_eq!(
(other.width, other.height, other.count),
(stats[0].width, stats[0].height, stats[0].count),
"traffic lights differ in size"
);
}
let pitch = (TRAFFIC_LIGHT_PITCH * RENDER_SCALE) as i64;
for (index, stat) in stats.iter().enumerate() {
assert_eq!(
stat.origin.1, stats[0].origin.1,
"traffic lights are not on the same line"
);
assert_eq!(
stat.origin.0 as i64 - stats[0].origin.0 as i64,
pitch * index as i64,
"traffic light {index} is misplaced"
);
}
let (x0, y0) = stats[0].origin;
let side = stats[0].width - 1;
for (dx, dy) in [(0, 0), (side, 0), (0, side), (side, side)] {
assert_ne!(
*img.get_pixel(x0 + dx, y0 + dy),
colors[0],
"the button fills its bounding box corner, so it is not a circle"
);
}
}
#[test]
fn draw_circle_is_a_symmetric_antialiased_disc() {
let renderer = bare_renderer();
let mut img: RgbaImage = ImageBuffer::from_pixel(41, 41, Rgba([0, 0, 0, 0]));
let (cx, cy, r) = (20.0f32, 20.0f32, 10.0f32);
renderer.draw_circle(&mut img, cx, cy, r, Rgba([255, 0, 0, 255]));
let opaque: Vec<(u32, u32)> = img
.enumerate_pixels()
.filter(|(_, _, p)| p[3] == 255)
.map(|(x, y, _)| (x, y))
.collect();
let xs: Vec<u32> = opaque.iter().map(|p| p.0).collect();
let ys: Vec<u32> = opaque.iter().map(|p| p.1).collect();
let (x0, x1) = (*xs.iter().min().unwrap(), *xs.iter().max().unwrap());
let (y0, y1) = (*ys.iter().min().unwrap(), *ys.iter().max().unwrap());
assert_eq!(x1 - x0, y1 - y0, "the disc is not as wide as it is tall");
for (x, y) in &opaque {
let mirrored_x = (2.0 * cx - 1.0) as u32 - x;
let mirrored_y = (2.0 * cy - 1.0) as u32 - y;
assert_eq!(
img.get_pixel(mirrored_x, *y)[3],
255,
"no horizontal mirror for ({x}, {y})"
);
assert_eq!(
img.get_pixel(*x, mirrored_y)[3],
255,
"no vertical mirror for ({x}, {y})"
);
}
assert_eq!(img.get_pixel(x0, y0)[3], 0);
assert_eq!(img.get_pixel(x1, y1)[3], 0);
for (x, y) in [(cx + r + 1.0, cy), (cx, cy + r + 1.0)] {
assert_eq!(
img.get_pixel(x as u32, y as u32)[3],
0,
"ink outside the circle radius"
);
}
let partial = img.pixels().filter(|p| p[3] > 0 && p[3] < 255).count();
assert!(partial > 0, "circle edge is not anti-aliased");
}
#[test]
fn screen_text_keeps_colors_and_drops_terminal_bookkeeping() {
let captured = screen_of(
b"\x1b[?2004h$ echo hi\r\n\x1b[?2004l\r\x1b[1;36mhi\x1b[0m\r\n$ \r\x1b[0m\x1b[J",
6,
40,
);
let text = screen_ansi_text(&captured, 40);
assert!(
text.contains("$ echo hi"),
"command echo missing: {:?}",
text
);
assert!(text.contains("hi"), "output missing: {:?}", text);
assert!(text.contains('\u{1b}'), "colors were lost: {:?}", text);
assert!(
!text.contains("?2004"),
"bracketed paste leaked: {:?}",
text
);
assert_eq!(
text.lines().count(),
2,
"the erased trailing prompt should be gone: {:?}",
text
);
}
#[test]
fn screen_text_reemits_the_cells_own_sgr() {
let captured = screen_of(b"\x1b[1;36mMCP\x1b[0m ok\r\n", 3, 20);
let text = screen_ansi_text(&captured, 20);
assert!(
text.starts_with("\x1b[0;1;36mMCP"),
"unexpected text: {:?}",
text
);
assert!(text.ends_with("\x1b[0m"), "line not reset: {:?}", text);
}
#[test]
fn screen_text_is_one_line_per_row() {
let captured = screen_of(b"abcdefghijklmno\r\n", 4, 10);
let text = screen_ansi_text(&captured, 10);
assert_eq!(text.lines().count(), 2);
assert!(text.contains("abcdefghij"));
assert!(text.contains("klmno"));
}
#[test]
fn render_bytes_renders_every_line_that_scrolled_off() {
let mut renderer = bare_renderer();
renderer.themes.insert("dark".to_string(), Theme::dark());
let out_dir = std::path::Path::new("target/full-capture-out");
std::fs::create_dir_all(out_dir).unwrap();
let data: String = (1..=200).map(|i| format!("line {}\r\n", i)).collect();
let (path, text, _, context) = renderer
.render_bytes_with_options(
data.as_bytes(),
40,
10,
out_dir,
Some("full capture"),
Some("dark"),
None,
None,
TextOptions {
strip_ansi: true,
embed_description: true,
..TextOptions::default()
},
true,
RenderOptions::default(),
)
.unwrap();
assert!(!context.truncated);
assert!(
text.starts_with("line 1\n"),
"text starts: {:?}",
&text[..20]
);
assert!(text.trim_end().ends_with("line 200"));
let img = image::open(&path).unwrap().to_rgba8();
let cell_h = renderer.default_fonts.cell_height * RENDER_SCALE;
let padding = renderer.padding * RENDER_SCALE;
assert_eq!(img.height(), 200 * cell_h + padding * 2);
let description = read_png_description(&path).expect("description");
assert!(description.starts_with("line 1\n"));
assert!(description.ends_with("line 200"));
std::fs::remove_file(&path).ok();
}
#[test]
fn styling_survives_from_the_oldest_scrollback_rows() {
let renderer = bare_renderer();
let mut data = String::from("\x1b[1;31mALERT\x1b[0m first\r\n");
for i in 2..=100 {
data.push_str(&format!("line {}\r\n", i));
}
let captured = renderer.capture(data.as_bytes(), 10, 40, LineSelection::All);
let cell = captured.cell(0, 0).expect("first cell");
assert_eq!(cell.contents(), "A");
assert_eq!(cell.fgcolor(), vt100::Color::Idx(1));
assert!(cell.bold());
let text = screen_ansi_text(&captured, 40);
assert!(
text.starts_with("\x1b[0;1;31mALERT"),
"scrollback style lost: {:?}",
&text[..24]
);
}
#[test]
fn head_and_tail_selections_narrow_the_render() {
let mut renderer = bare_renderer();
renderer.themes.insert("dark".to_string(), Theme::dark());
let out_dir = std::path::Path::new("target/selection-out");
std::fs::create_dir_all(out_dir).unwrap();
let data: String = (1..=200).map(|i| format!("line {}\r\n", i)).collect();
let render = |lines| {
renderer
.render_bytes_with_options(
data.as_bytes(),
40,
10,
out_dir,
Some("selection"),
Some("dark"),
None,
None,
TextOptions {
strip_ansi: true,
..TextOptions::default()
},
true,
RenderOptions::default().with_lines(lines),
)
.unwrap()
};
let (head_path, head_text, _, head_context) = render(LineSelection::Head(10));
assert_eq!(head_context.lines, LineSelection::Head(10));
assert_eq!(head_text.lines().count(), 10);
assert_eq!(head_text.lines().next().unwrap(), "line 1");
assert_eq!(head_text.lines().last().unwrap(), "line 10");
let (tail_path, tail_text, _, tail_context) = render(LineSelection::Tail(10));
assert_eq!(tail_context.lines, LineSelection::Tail(10));
assert_eq!(tail_text.lines().count(), 10);
assert_eq!(tail_text.lines().next().unwrap(), "line 191");
assert_eq!(tail_text.lines().last().unwrap(), "line 200");
let cell_h = renderer.default_fonts.cell_height * RENDER_SCALE;
let padding = renderer.padding * RENDER_SCALE;
for path in [&head_path, &tail_path] {
let img = image::open(path).unwrap().to_rgba8();
assert_eq!(img.height(), 10 * cell_h + padding * 2);
std::fs::remove_file(path).ok();
}
}
#[test]
fn an_oversized_capture_is_refused_with_advice() {
let mut renderer = bare_renderer();
renderer.themes.insert("dark".to_string(), Theme::dark());
let out_dir = std::path::Path::new("target/oversized-out");
std::fs::create_dir_all(out_dir).unwrap();
let data: String = (1..=12_000).map(|i| format!("line {}\r\n", i)).collect();
let err = renderer
.render_bytes(
data.as_bytes(),
200,
10,
out_dir,
Some("oversized"),
Some("dark"),
None,
None,
TextOptions::default(),
false,
)
.expect_err("an image this size must be refused");
let message = err.to_string();
assert!(
message.contains("--head-lines") && message.contains("megapixels"),
"unhelpful error: {message}"
);
}
#[test]
fn the_render_budget_counts_every_simultaneous_buffer() {
let screen = screen_of(b"hi", 4, 80);
let side = (MAX_IMAGE_PIXELS as f64).sqrt() as u32;
assert!(check_render_budget(side, side, 1, &screen).is_ok());
let err = check_render_budget(side, side, 2, &screen)
.expect_err("two buffers of a 64 MP image exceed the budget");
assert!(
err.to_string().contains("MB of image buffers"),
"the error should name the memory cost: {err}"
);
assert!(check_render_budget(side + 1, side + 1, 1, &screen).is_err());
}
#[test]
fn huge_geometry_is_refused_before_allocation() {
let mut renderer = bare_renderer();
renderer.themes.insert("dark".to_string(), Theme::dark());
let out_dir = std::path::Path::new("target/huge-geometry-out");
std::fs::create_dir_all(out_dir).unwrap();
let render = |cols: u16, rows: u16, data: &str, chrome: Option<&ChromeOptions>| {
renderer.render_bytes(
data.as_bytes(),
cols,
rows,
out_dir,
Some("huge"),
Some("dark"),
chrome,
None,
TextOptions::default(),
false,
)
};
let tall: String = (1..=12_000).map(|i| format!("line {}\r\n", i)).collect();
let err = render(200, 10, &tall, None).expect_err("a 12,000-line image must be refused");
assert!(err.to_string().contains("--head-lines"), "{err}");
let wide = format!("{}\r\n", "x".repeat(500)).repeat(2_000);
let err = render(500, 10, &wide, None).expect_err("a 500-column wall must be refused");
assert!(err.to_string().contains("--head-lines"), "{err}");
let (path, _, _, _) = renderer
.render_bytes_with_options(
tall.as_bytes(),
200,
10,
out_dir,
Some("huge-head"),
Some("dark"),
None,
None,
TextOptions::default(),
false,
RenderOptions::default().with_lines(LineSelection::Head(20)),
)
.expect("a twenty-line selection is renderable");
std::fs::remove_file(&path).ok();
}
#[test]
fn head_selection_survives_a_capture_larger_than_the_scrollback() {
let mut renderer = bare_renderer();
renderer.max_scrollback_lines = 100;
renderer.themes.insert("dark".to_string(), Theme::dark());
let out_dir = std::path::Path::new("target/head-overflow-out");
std::fs::create_dir_all(out_dir).unwrap();
let data: String = (1..=20_000).map(|i| format!("line {}\r\n", i)).collect();
let (path, text, _, context) = renderer
.render_bytes_with_options(
data.as_bytes(),
80,
24,
out_dir,
Some("head-overflow"),
Some("dark"),
None,
None,
TextOptions {
strip_ansi: true,
..TextOptions::default()
},
true,
RenderOptions::default().with_lines(LineSelection::Head(10)),
)
.unwrap();
let lines: Vec<&str> = text.lines().collect();
assert_eq!(lines.len(), 10);
assert_eq!(lines[0], "line 1");
assert_eq!(lines[9], "line 10");
assert!(
!context.truncated,
"the head is complete, so nothing it shows was dropped"
);
std::fs::remove_file(&path).ok();
}
#[test]
fn head_selection_ignores_the_configured_scrollback_capacity() {
let mut renderer = bare_renderer();
renderer.max_scrollback_lines = 1;
renderer.themes.insert("dark".to_string(), Theme::dark());
let out_dir = std::path::Path::new("target/head-tiny-capacity-out");
std::fs::create_dir_all(out_dir).unwrap();
let data: String = (1..=1_000).map(|i| format!("line {}\r\n", i)).collect();
let (path, text, _, context) = renderer
.render_bytes_with_options(
data.as_bytes(),
80,
40,
out_dir,
Some("head-tiny-capacity"),
Some("dark"),
None,
None,
TextOptions {
strip_ansi: true,
..TextOptions::default()
},
true,
RenderOptions::default().with_lines(LineSelection::Head(10)),
)
.unwrap();
let lines: Vec<&str> = text.lines().collect();
let expected: Vec<String> = (1..=10).map(|i| format!("line {}", i)).collect();
assert_eq!(lines, expected);
assert!(!context.truncated);
std::fs::remove_file(&path).ok();
}
#[test]
fn render_meta_reports_truncation_exactly() {
let mut renderer = bare_renderer();
renderer.max_scrollback_lines = 10;
renderer.themes.insert("dark".to_string(), Theme::dark());
let out_dir = std::path::Path::new("target/truncation-meta-out");
std::fs::create_dir_all(out_dir).unwrap();
let render = |lines: usize| {
let data: String = (1..=lines).map(|i| format!("line {}\r\n", i)).collect();
renderer
.render_bytes_with_options(
data.as_bytes(),
40,
5,
out_dir,
Some("truncation"),
Some("dark"),
None,
None,
TextOptions::default(),
true,
RenderOptions::default(),
)
.unwrap()
};
let (path, _, _, context) = render(14);
assert!(!context.truncated);
std::fs::remove_file(&path).ok();
let (path, _, _, context) = render(15);
assert!(context.truncated);
std::fs::remove_file(&path).ok();
}
#[test]
fn effective_scrollback_follows_the_terminal_width() {
let renderer = bare_renderer();
assert_eq!(
renderer.effective_scrollback_lines(40, 120),
DEFAULT_MAX_SCROLLBACK_LINES
);
assert!(renderer.effective_scrollback_lines(40, 500) < DEFAULT_MAX_SCROLLBACK_LINES);
}
#[test]
fn chrome_composition_is_pixel_identical_with_one_fewer_buffer() {
let renderer = bare_renderer();
let theme = Theme::dark();
let captured = screen_of(b"\x1b[1;32mok\x1b[0m composed", 4, 40);
for (preset, shadow, rounded) in [
("gnome", true, true),
("macos", false, true),
("minimal", true, false),
("report", false, false),
] {
let chrome = ChromeOptions {
enabled: true,
preset: preset.to_string(),
title: Some("demo".to_string()),
timestamp: false,
shadow,
radius: 14,
rounded,
outer_padding: 18,
title_bar_height: 34,
};
let one_layer = renderer
.render_to_image(
&captured,
&theme,
&renderer.default_fonts,
&chrome,
None,
true,
)
.unwrap();
let terminal = renderer
.render_screen(&captured, &theme, &renderer.default_fonts, None, true)
.unwrap();
let copied =
renderer.compose_with_chrome(terminal, &theme, &renderer.default_fonts, &chrome);
assert_eq!(
one_layer.dimensions(),
copied.dimensions(),
"{preset} changed size"
);
assert!(
one_layer.as_raw() == copied.as_raw(),
"{preset} (shadow={shadow}) is no longer pixel identical"
);
}
}
const SHAPE_A: &str = "tests/fixtures/shape-a.ttf";
const SHAPE_B: &str = "tests/fixtures/shape-b.ttf";
const COLOR_EMOJI: &str = "tests/fixtures/color-emoji.ttf";
const COLLECTION: &str = "tests/fixtures/collection.ttc";
const DEVANAGARI_KA: char = '\u{0915}';
fn cell_at(screen: &CapturedScreen, col: u16) -> &vt100::Cell {
screen.cell(0, col).expect("cell in range")
}
#[test]
fn ordinary_output_never_reaches_the_shaper() {
let renderer = renderer_with(None, &[]);
let fonts = &renderer.default_fonts;
let plain = "abc XYZ 019 => != -> <= |> ::";
let captured = screen_of(plain.as_bytes(), 2, 40);
for col in 0..plain.chars().count() as u16 {
assert!(
!renderer.cell_needs_shaping(fonts, cell_at(&captured, col)),
"ASCII cell {col} was sent to the shaper"
);
}
for text in [
"\u{250C}\u{2500}\u{2510}\u{2502}\u{2514}\u{2518}",
"\u{03B1}\u{03B2}\u{0416}\u{0429}",
] {
let captured = screen_of(text.as_bytes(), 2, 20);
for col in 0..text.chars().count() as u16 {
assert!(
!renderer.cell_needs_shaping(fonts, cell_at(&captured, col)),
"{text:?} cell {col} was sent to the shaper"
);
}
}
}
#[test]
fn only_cells_the_fast_path_cannot_draw_are_shaped() {
let renderer = renderer_with(None, &[]);
let fonts = &renderer.default_fonts;
let corpus: &[(&str, u16, &str)] = &[
("e\u{0301}", 0, "base plus combining mark is one cell"),
("1\u{FE0F}\u{20E3}", 0, "keycap sequence is one cell"),
("\u{2764}\u{FE0F}", 0, "variation selector sequence"),
("\u{1F600}", 0, "emoji presentation"),
("\u{1F44D}\u{1F3FD}", 0, "emoji plus skin tone modifier"),
("\u{1F1FA}\u{1F1F8}", 0, "regional indicators"),
("\u{0645}\u{0631}", 0, "Arabic joins"),
("\u{0915}\u{094D}\u{0937}", 1, "Devanagari reorders"),
("\u{4F60}", 0, "no configured font covers this CJK"),
];
for (text, col, why) in corpus {
let captured = screen_of(text.as_bytes(), 2, 20);
assert!(
renderer.cell_needs_shaping(fonts, cell_at(&captured, *col)),
"{text:?} column {col} should be shaped: {why}"
);
}
}
#[test]
fn disabling_shaping_turns_the_whole_path_off() {
let renderer = renderer_with_shaping(None, &[], ShapingOptions::disabled());
assert!(!renderer.default_fonts.shaping().enabled());
assert!(renderer.default_fonts.shaping().families().is_empty());
}
#[test]
fn a_shaped_run_stops_at_a_style_boundary() {
let renderer = renderer_with(None, &[]);
let fonts = &renderer.default_fonts;
let captured = screen_of("\u{0645}\u{001b}[31m\u{0631}\u{001b}[0m".as_bytes(), 2, 20);
let run = renderer.collect_shaped_run(&captured, fonts, 0, 0, 20, None);
assert_eq!(
run.cells.len(),
1,
"the run crossed a style boundary: {:?}",
run.cells
);
let captured = screen_of("\u{0645}\u{0631}".as_bytes(), 2, 20);
let run = renderer.collect_shaped_run(&captured, fonts, 0, 0, 20, None);
assert_eq!(
run.cells.len(),
2,
"same-style Arabic did not shape as one run"
);
}
#[test]
fn an_arabic_phrase_shapes_across_its_space() {
let renderer = renderer_with(None, &[]);
let fonts = &renderer.default_fonts;
let phrase = "\u{0645}\u{0631}\u{062D}\u{0628}\u{0627} \
\u{0628}\u{0627}\u{0644}\u{0639}\u{0627}\u{0644}\u{0645}";
let captured = screen_of(phrase.as_bytes(), 2, 30);
let run = renderer.collect_shaped_run(&captured, fonts, 0, 0, 30, None);
assert_eq!(
run.cells
.iter()
.map(|cell| cell.text.as_str())
.collect::<String>(),
phrase
);
assert_eq!(run.cols, phrase.chars().count() as u32);
}
#[test]
fn a_supported_width_arabic_phrase_stays_in_one_run() {
let renderer = renderer_with(None, &[]);
let fonts = &renderer.default_fonts;
let phrase = "\u{0645}\u{0631}\u{062D}\u{0628}\u{0627} ".repeat(80);
let captured = screen_of(phrase.as_bytes(), 2, 500);
let run = renderer.collect_shaped_run(&captured, fonts, 0, 0, 500, None);
assert!(
run.cols > 256 && run.cols <= 500,
"fixture must cross the ordinary shaping limit"
);
assert_eq!(
run.cells
.iter()
.map(|cell| cell.text.as_str())
.collect::<String>(),
phrase.trim_end()
);
}
#[test]
fn a_shaped_run_stops_where_the_shaping_kind_changes() {
let renderer = renderer_with(None, &[]);
let fonts = &renderer.default_fonts;
let captured = screen_of("\u{0645}\u{1F600}".as_bytes(), 2, 20);
let run = renderer.collect_shaped_run(&captured, fonts, 0, 0, 20, None);
assert_eq!(run.cells.len(), 1, "an emoji joined an Arabic run");
let captured = screen_of("\u{1F44D}\u{1F3FD}".as_bytes(), 2, 20);
let run = renderer.collect_shaped_run(&captured, fonts, 0, 0, 20, None);
assert_eq!(
run.cells.len(),
2,
"a split emoji sequence did not shape as one run"
);
assert_eq!(run.cols, 4, "the run must own every column vt100 gave it");
}
#[test]
fn a_shaped_run_stops_at_a_redaction_boundary() {
use crate::redaction::RedactionMap;
let renderer = renderer_with(None, &[]);
let fonts = &renderer.default_fonts;
let captured = screen_of("\u{0645}\u{0631}\u{062D}".as_bytes(), 2, 20);
let mut map = RedactionMap::default();
map.add_manual(0, 1, 2, None);
let run = renderer.collect_shaped_run(&captured, fonts, 0, 0, 20, Some(&map));
assert_eq!(
run.cells.len(),
1,
"the run ran into a redacted cell: {:?}",
run.cells
);
}
#[test]
fn configured_font_order_decides_a_shaped_glyph() {
let ka = DEVANAGARI_KA.to_string();
for (fallbacks, expect_left) in [([SHAPE_A, SHAPE_B], true), ([SHAPE_B, SHAPE_A], false)] {
let renderer = renderer_with(None, &fallbacks);
let img = render_line(&renderer, &ka, 6);
let cell_w = renderer.default_fonts.cell_width * RENDER_SCALE;
let padding = renderer.padding * RENDER_SCALE;
let left = ink_in_columns(&img, padding, padding + cell_w / 2);
let right = ink_in_columns(&img, padding + cell_w / 2, padding + cell_w);
if expect_left {
assert!(
left > right,
"{fallbacks:?}: expected the first font's left bar, got left={left} right={right}"
);
} else {
assert!(
right > left,
"{fallbacks:?}: expected the first font's right bar, got left={left} right={right}"
);
}
}
}
#[test]
fn shaped_font_precedence_matches_the_configured_chain() {
let renderer = renderer_with(Some(LIMITED_PRIMARY), &[SHAPE_A, SHAPE_B]);
assert_eq!(
renderer.default_fonts.shaping().families(),
vec![
"Termshot Test ASCII".to_string(),
"JetBrains Mono".to_string(),
"Termshot Shape A".to_string(),
"Termshot Shape B".to_string(),
]
);
}
#[test]
fn font_collection_faces_keep_their_indices() {
let renderer = renderer_with(None, &[COLLECTION]);
let faces = renderer.default_fonts.shaping().loaded_faces();
assert!(
faces.contains(&("Termshot Collection Zero".to_string(), 0)),
"face 0 missing from {faces:?}"
);
assert!(
faces.contains(&("Termshot Collection One".to_string(), 1)),
"face 1 missing from {faces:?}"
);
}
#[test]
fn a_glyph_only_in_the_second_collection_face_still_renders() {
let renderer = renderer_with(Some(LIMITED_PRIMARY), &[COLLECTION]);
assert!(
ink(&render_line(&renderer, "\u{E021}", 6)) > 0,
"the second collection face was never reached"
);
assert_eq!(
ink(&render_line(&renderer, "\u{E022}", 6)),
0,
"a code point no configured face covers must stay blank"
);
}
#[test]
fn emoji_presentation_uses_a_configured_color_font() {
let renderer = renderer_with(None, &[COLOR_EMOJI]);
assert_eq!(
renderer.default_fonts.shaping().emoji_family().as_deref(),
Some("Termshot Color Emoji")
);
let img = render_line(&renderer, "\u{1F600}", 6);
let reds = count_near(&img, Rgba([255, 0, 0, 255]));
let blues = count_near(&img, Rgba([0, 0, 255, 255]));
assert!(
reds > 0 && blues > 0,
"color layers missing: {reds} red, {blues} blue pixels"
);
}
#[test]
fn variation_selectors_choose_the_presentation() {
let renderer = renderer_with(None, &[SHAPE_A, COLOR_EMOJI]);
let emoji = render_line(&renderer, "\u{2764}\u{FE0F}", 6);
assert!(
count_near(&emoji, Rgba([255, 0, 0, 255])) > 0
&& count_near(&emoji, Rgba([0, 0, 255, 255])) > 0,
"VS16 did not select the color font"
);
let text = render_line(&renderer, "\u{2764}\u{FE0E}", 6);
assert_eq!(
count_near(&text, Rgba([0, 0, 255, 255])),
0,
"VS15 must keep the text presentation, not the color font"
);
assert!(ink(&text) > 0, "VS15 drew no glyph at all");
}
#[test]
fn the_renderer_stays_shareable_across_threads() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<Renderer>();
assert_send_sync::<ThemeFonts>();
}
fn count_near(img: &RgbaImage, want: Rgba<u8>) -> usize {
img.pixels()
.filter(|p| (0..3).all(|i| (p[i] as i32 - want[i] as i32).abs() <= 40) && p[3] > 200)
.count()
}
}