use base64::Engine;
use image::{ImageBuffer, Rgba, RgbaImage};
pub const EXPLORER_SRC_SVG: &[u8] = include_bytes!("../assets/icons/files.svg");
pub const SEARCH_SRC_SVG: &[u8] = include_bytes!("../assets/icons/search.svg");
pub const SOURCE_CONTROL_SRC_SVG: &[u8] = include_bytes!("../assets/icons/source-control.svg");
pub const REMOTE_SRC_SVG: &[u8] = include_bytes!("../assets/icons/remote-explorer.svg");
pub const RUN_DEBUG_SRC_SVG: &[u8] = include_bytes!("../assets/icons/debug-alt.svg");
pub const EXTENSIONS_SRC_SVG: &[u8] = include_bytes!("../assets/icons/extensions.svg");
pub const TESTING_SRC_SVG: &[u8] = include_bytes!("../assets/icons/beaker.svg");
pub const CODEQL_SRC_SVG: &[u8] = include_bytes!("../assets/icons/ql.svg");
pub const SETTINGS_GEAR_SRC_SVG: &[u8] = include_bytes!("../assets/icons/settings_gear.svg");
pub const SPONSOR_HEART_SRC_SVG: &[u8] = include_bytes!("../assets/icons/heart.svg");
pub const LAYOUT_SIDEBAR_ON_SRC_SVG: &[u8] =
include_bytes!("../assets/icons/layout-sidebar-left.svg");
pub const LAYOUT_SIDEBAR_OFF_SRC_SVG: &[u8] =
include_bytes!("../assets/icons/layout-sidebar-left-off.svg");
pub const LAYOUT_PANEL_ON_SRC_SVG: &[u8] = include_bytes!("../assets/icons/layout-panel.svg");
pub const LAYOUT_PANEL_OFF_SRC_SVG: &[u8] = include_bytes!("../assets/icons/layout-panel-off.svg");
pub const LAYOUT_CUSTOMIZE_SRC_SVG: &[u8] = include_bytes!("../assets/icons/layout.svg");
pub const RUN_DEBUG_SRC_PNG: &[u8] = include_bytes!("../assets/icons/run_debug_src.png");
pub const WELCOME_LOGO_PNG: &[u8] = include_bytes!("../assets/logo-tight-removebg-preview.png");
pub const APP_ICON_PNG: &[u8] = include_bytes!("../assets/logo.png");
pub const NO_REPO_HERO_PNG: &[u8] = include_bytes!("../assets/icons/no_repo_src.png");
pub const SSH_EMPTY_STATE_PNG: &[u8] = include_bytes!("../assets/icons/ssh_empty_state.png");
const ACTIVE_PILL: Rgba<u8> = Rgba([0x4e, 0x9a, 0xff, 0xff]);
const ACTIVE_TINT: Rgba<u8> = Rgba([0xff, 0xff, 0xff, 0xff]);
const INACTIVE_TINT: Rgba<u8> = Rgba([0x9d, 0xa5, 0xb4, 0xff]);
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct IconInk {
pub inactive: Rgba<u8>,
pub active: Rgba<u8>,
pub pill: Rgba<u8>,
}
impl Default for IconInk {
fn default() -> Self {
Self {
inactive: INACTIVE_TINT,
active: ACTIVE_TINT,
pill: ACTIVE_PILL,
}
}
}
impl IconInk {
pub fn new(inactive: (u8, u8, u8), active: (u8, u8, u8), pill: (u8, u8, u8)) -> Self {
let opaque = |(r, g, b): (u8, u8, u8)| Rgba([r, g, b, 0xff]);
Self {
inactive: opaque(inactive),
active: opaque(active),
pill: opaque(pill),
}
}
fn tint(self, state: IconState) -> Rgba<u8> {
if state.tinted() {
self.active
} else {
self.inactive
}
}
}
pub fn compose_icon(
src_codicon_png: &[u8],
canvas_w: u32,
canvas_h: u32,
is_active: bool,
ink: IconInk,
bg: Rgba<u8>,
off_y_bias: i64,
) -> Result<Vec<u8>, image::ImageError> {
let codicon =
image::load_from_memory_with_format(src_codicon_png, image::ImageFormat::Png)?.to_rgba8();
let (src_w, src_h) = (codicon.width().max(1), codicon.height().max(1));
let (icon_w, icon_h) = fit_icon_dims(canvas_w, canvas_h, src_w, src_h);
let scaled = image::imageops::resize(
&codicon,
icon_w,
icon_h,
image::imageops::FilterType::Lanczos3,
);
let tint = ink.tint(if is_active {
IconState::Active
} else {
IconState::Inactive
});
let tinted = tint_rgba(&scaled, tint);
Ok(finish_icon(
&tinted, canvas_w, canvas_h, is_active, ink.pill, bg, off_y_bias,
))
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum IconState {
Inactive,
Hovered,
Active,
}
impl IconState {
fn tinted(self) -> bool {
matches!(self, IconState::Hovered | IconState::Active)
}
fn pill(self) -> bool {
matches!(self, IconState::Active)
}
}
pub fn compose_icon_svg(
src_svg: &[u8],
canvas_w: u32,
canvas_h: u32,
state: IconState,
ink: IconInk,
bg: Rgba<u8>,
off_y_bias: i64,
) -> Option<Vec<u8>> {
let tree = resvg::usvg::Tree::from_data(src_svg, &resvg::usvg::Options::default()).ok()?;
let size = tree.size();
let (src_w, src_h) = (
size.width().ceil().max(1.0) as u32,
size.height().ceil().max(1.0) as u32,
);
let (icon_w, icon_h) = fit_icon_dims(canvas_w, canvas_h, src_w, src_h);
let mut pixmap = resvg::tiny_skia::Pixmap::new(icon_w, icon_h)?;
let transform = resvg::tiny_skia::Transform::from_scale(
icon_w as f32 / size.width(),
icon_h as f32 / size.height(),
);
resvg::render(&tree, transform, &mut pixmap.as_mut());
let tint = ink.tint(state);
let data = pixmap.data();
let mut glyph: RgbaImage = ImageBuffer::new(icon_w, icon_h);
for (i, px) in glyph.pixels_mut().enumerate() {
*px = Rgba([tint.0[0], tint.0[1], tint.0[2], data[i * 4 + 3]]);
}
Some(finish_icon(
&glyph,
canvas_w,
canvas_h,
state.pill(),
ink.pill,
bg,
off_y_bias,
))
}
fn fit_icon_dims(canvas_w: u32, canvas_h: u32, src_w: u32, src_h: u32) -> (u32, u32) {
let target_max = (canvas_w.min(canvas_h).saturating_sub(4) * 9 / 10).max(8);
let (src_w, src_h) = (src_w.max(1), src_h.max(1));
if src_w <= src_h {
let scaled_h = ((target_max * src_h) / src_w).max(1);
let capped_h = scaled_h.min(canvas_h.saturating_sub(2).max(1));
let final_w = ((capped_h * src_w) / src_h).max(1);
(final_w, capped_h)
} else {
let scaled_w = ((target_max * src_w) / src_h).max(1);
let capped_w = scaled_w.min(canvas_w.saturating_sub(2).max(1));
let final_h = ((capped_w * src_h) / src_w).max(1);
(capped_w, final_h)
}
}
fn finish_icon(
tinted: &RgbaImage,
canvas_w: u32,
canvas_h: u32,
is_active: bool,
pill_color: Rgba<u8>,
bg: Rgba<u8>,
off_y_bias: i64,
) -> Vec<u8> {
let (icon_w, icon_h) = (tinted.width(), tinted.height());
let mut canvas: RgbaImage = ImageBuffer::from_pixel(canvas_w, canvas_h, bg);
let off_x = ((canvas_w.saturating_sub(icon_w)) / 2) as i64;
let centered_off_y = (canvas_h.saturating_sub(icon_h)) / 2;
let max_off_y = canvas_h.saturating_sub(icon_h) as i64;
let off_y = (centered_off_y as i64 + off_y_bias).clamp(0, max_off_y);
image::imageops::overlay(&mut canvas, tinted, off_x, off_y);
if is_active {
let pill_w: u32 = if canvas_w >= 8 { 2 } else { 1 };
let pill_y_start = off_y.max(0) as u32;
let pill_y_end = (pill_y_start + icon_h).min(canvas_h);
for y in pill_y_start..pill_y_end {
for x in 0..pill_w {
canvas.put_pixel(x, y, pill_color);
}
}
}
let mut out = Vec::with_capacity(2048);
let _ = image::DynamicImage::ImageRgba8(canvas)
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png);
out
}
pub fn count_badge_cells_w(count: usize) -> u16 {
if count > 99 { 3 } else { 2 }
}
const BADGE_GLYPHS: [(char, [u8; 5]); 11] = [
('0', [0b111, 0b101, 0b101, 0b101, 0b111]),
('1', [0b010, 0b110, 0b010, 0b010, 0b111]),
('2', [0b111, 0b001, 0b111, 0b100, 0b111]),
('3', [0b111, 0b001, 0b111, 0b001, 0b111]),
('4', [0b101, 0b101, 0b111, 0b001, 0b001]),
('5', [0b111, 0b100, 0b111, 0b001, 0b111]),
('6', [0b111, 0b100, 0b111, 0b101, 0b111]),
('7', [0b111, 0b001, 0b010, 0b010, 0b010]),
('8', [0b111, 0b101, 0b111, 0b101, 0b111]),
('9', [0b111, 0b101, 0b111, 0b001, 0b111]),
('+', [0b000, 0b010, 0b111, 0b010, 0b000]),
];
pub fn compose_count_badge(
count: usize,
cell_w: u32,
cell_h: u32,
accent: (u8, u8, u8),
bg: Rgba<u8>,
) -> Option<Vec<u8>> {
let label = if count > 99 {
String::from("99+")
} else {
count.to_string()
};
let (w, h) = (cell_w * count_badge_cells_w(count) as u32, cell_h);
if w == 0 || h == 0 {
return None;
}
let mut canvas: RgbaImage = ImageBuffer::from_pixel(w, h, bg);
let accent_px = Rgba([accent.0, accent.1, accent.2, 0xff]);
let r = h as f32 / 2.0;
for y in 0..h {
for x in 0..w {
let (fx, fy) = (x as f32 + 0.5, y as f32 + 0.5);
let cx = fx.clamp(r, (w as f32 - r).max(r));
let cy = fy.clamp(r, (h as f32 - r).max(r));
if (fx - cx).hypot(fy - cy) <= r {
canvas.put_pixel(x, y, accent_px);
}
}
}
let glyphs: Vec<&[u8; 5]> = label
.chars()
.filter_map(|c| {
BADGE_GLYPHS
.iter()
.find(|(g, _)| *g == c)
.map(|(_, rows)| rows)
})
.collect();
let n = glyphs.len() as u32;
if n > 0 {
let grid_w = n * 3 + (n - 1); let scale = ((h * 6 / 10) / 5).min((w * 8 / 10) / grid_w).max(1);
let off_x = w.saturating_sub(grid_w * scale) / 2;
let off_y = h.saturating_sub(5 * scale) / 2;
let white = Rgba([0xff, 0xff, 0xff, 0xff]);
for (gi, rows) in glyphs.iter().enumerate() {
let gx = off_x + gi as u32 * 4 * scale;
for (ry, row) in rows.iter().enumerate() {
for col in 0..3u32 {
if row & (0b100 >> col) == 0 {
continue;
}
let (px0, py0) = (gx + col * scale, off_y + ry as u32 * scale);
for dy in 0..scale {
for dx in 0..scale {
let (px, py) = (px0 + dx, py0 + dy);
if px < w && py < h {
canvas.put_pixel(px, py, white);
}
}
}
}
}
}
}
let mut out = Vec::with_capacity(1024);
let _ = image::DynamicImage::ImageRgba8(canvas)
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png);
Some(out)
}
fn tint_rgba(src: &RgbaImage, tint: Rgba<u8>) -> RgbaImage {
let mut out = src.clone();
for px in out.pixels_mut() {
let a = px.0[3];
px.0 = [tint.0[0], tint.0[1], tint.0[2], a];
}
out
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InlineImageProtocol {
ITerm2,
Kitty,
Sixel,
None,
}
pub fn inline_image_protocol_for(
term_program: Option<&str>,
term: Option<&str>,
) -> InlineImageProtocol {
match term_program {
Some("iTerm.app") | Some("WezTerm") => InlineImageProtocol::ITerm2,
Some("ghostty") => InlineImageProtocol::Kitty,
Some(CROFT_TERM_PROGRAM) => InlineImageProtocol::ITerm2,
_ if term.is_some_and(|t| t.contains("kitty") || t.contains("ghostty")) => {
InlineImageProtocol::Kitty
}
_ => InlineImageProtocol::None,
}
}
pub fn terminal_warrants_switch_warning(protocol: InlineImageProtocol, termux: bool) -> bool {
protocol == InlineImageProtocol::None && !termux
}
pub const CROFT_TERM_PROGRAM: &str = "croft";
pub const CROFT_INLINE_IMAGES_ENV: &str = "CROFT_INLINE_IMAGES";
pub fn inline_image_protocol_in(
term_program: Option<&str>,
term: Option<&str>,
croft_inline_images: Option<&str>,
) -> InlineImageProtocol {
if term_program == Some(CROFT_TERM_PROGRAM) && croft_inline_images != Some("1") {
return InlineImageProtocol::None;
}
inline_image_protocol_for(term_program, term)
}
pub fn detect_inline_image_protocol() -> InlineImageProtocol {
let term_program = std::env::var("TERM_PROGRAM").ok();
let term = std::env::var("TERM").ok();
let protocol = inline_image_protocol_in(
term_program.as_deref(),
term.as_deref(),
std::env::var(CROFT_INLINE_IMAGES_ENV).ok().as_deref(),
);
if protocol != InlineImageProtocol::None {
return protocol;
}
if force_inline_images(std::env::var("CROFT_FORCE_INLINE_IMAGES").ok().as_deref()) {
return InlineImageProtocol::ITerm2;
}
InlineImageProtocol::None
}
pub fn da1_advertises_sixel(reply: &[u8]) -> bool {
let text = String::from_utf8_lossy(reply);
let Some(start) = text.find("\x1b[?") else {
return false;
};
let tail = &text[start + 3..];
let Some(end) = tail.find('c') else {
return false;
};
tail[..end].split(';').any(|tok| tok.trim() == "4")
}
#[cfg(unix)]
pub fn probe_sixel_support() -> bool {
use std::io::{Read, Write};
use std::os::fd::AsRawFd;
let mut out = std::io::stdout();
if out.write_all(b"\x1b[c").is_err() || out.flush().is_err() {
return false;
}
let stdin = std::io::stdin();
let fd = stdin.as_raw_fd();
let mut buf = Vec::with_capacity(32);
let mut byte = [0u8; 1];
let deadline = std::time::Instant::now() + std::time::Duration::from_millis(250);
loop {
let remaining = deadline.saturating_duration_since(std::time::Instant::now());
if remaining.is_zero() {
break;
}
let mut pfd = libc::pollfd {
fd,
events: libc::POLLIN,
revents: 0,
};
let ms = remaining.as_millis().min(i32::MAX as u128) as libc::c_int;
let n = unsafe { libc::poll(&mut pfd, 1, ms) };
if n <= 0 {
break; }
match stdin.lock().read(&mut byte) {
Ok(1) => {
buf.push(byte[0]);
if byte[0] == b'c' || buf.len() >= 64 {
break; }
}
_ => break,
}
}
da1_advertises_sixel(&buf)
}
pub fn is_termux_env(termux_version: Option<&str>, prefix: Option<&str>) -> bool {
termux_version.is_some_and(|v| !v.is_empty())
|| prefix.is_some_and(|p| p.contains("com.termux"))
}
pub fn detect_termux() -> bool {
static CACHE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*CACHE.get_or_init(|| {
is_termux_env(
std::env::var("TERMUX_VERSION").ok().as_deref(),
std::env::var("PREFIX").ok().as_deref(),
)
})
}
pub fn osk_env(termux: bool, force: Option<&str>) -> bool {
termux || force_inline_images(force)
}
pub fn detect_osk_auto() -> bool {
static CACHE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*CACHE.get_or_init(|| {
osk_env(
detect_termux(),
std::env::var("CROFT_FORCE_OSK").ok().as_deref(),
)
})
}
pub fn is_iterm2_term_program(value: Option<&str>) -> bool {
matches!(value, Some("iTerm.app") | Some("WezTerm"))
}
pub fn force_inline_images(value: Option<&str>) -> bool {
value.is_some_and(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"))
}
pub fn is_tmux_env(term: Option<&str>, tmux_var: Option<&str>) -> bool {
tmux_var.is_some_and(|v| !v.is_empty())
|| term.is_some_and(|v| v.starts_with("tmux") || v.starts_with("screen"))
}
pub fn detect_iterm2_inline_support() -> bool {
if force_inline_images(std::env::var("CROFT_FORCE_INLINE_IMAGES").ok().as_deref()) {
return true;
}
let term_program = std::env::var("TERM_PROGRAM").ok();
is_iterm2_term_program(term_program.as_deref())
}
pub fn detect_tmux() -> bool {
let term = std::env::var("TERM").ok();
let tmux = std::env::var("TMUX").ok();
is_tmux_env(term.as_deref(), tmux.as_deref())
}
pub fn fit_image(
src_png: &[u8],
canvas_w_px: u32,
canvas_h_px: u32,
bg: Rgba<u8>,
) -> Result<Vec<u8>, image::ImageError> {
fit_image_auto(src_png, canvas_w_px, canvas_h_px, bg)
}
pub fn fit_image_with_ink(
src_png: &[u8],
canvas_w_px: u32,
canvas_h_px: u32,
bg: Rgba<u8>,
ink: Option<(u8, u8, u8)>,
) -> Result<Vec<u8>, image::ImageError> {
let Some((ir, ig, ib)) = ink else {
return fit_image_auto(src_png, canvas_w_px, canvas_h_px, bg);
};
let mut img = image::load_from_memory(src_png)?.to_rgba8();
for px in img.pixels_mut() {
let [r, g, b, a] = px.0;
if a > 0 && r > 200 && g > 200 && b > 200 {
px.0 = [ir, ig, ib, a];
}
}
let mut recolored = Vec::with_capacity(src_png.len());
image::DynamicImage::ImageRgba8(img).write_to(
&mut std::io::Cursor::new(&mut recolored),
image::ImageFormat::Png,
)?;
fit_image_auto(&recolored, canvas_w_px, canvas_h_px, bg)
}
#[cfg(test)]
thread_local! {
pub static FIT_IMAGE_BAKES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
pub const MAX_DECODE_PIXELS: u64 = 128_000_000;
pub fn fit_image_auto(
src: &[u8],
canvas_w_px: u32,
canvas_h_px: u32,
bg: Rgba<u8>,
) -> Result<Vec<u8>, image::ImageError> {
#[cfg(test)]
FIT_IMAGE_BAKES.with(|c| c.set(c.get() + 1));
let format = image::guess_format(src)?;
let reader = || image::ImageReader::with_format(std::io::Cursor::new(src), format);
let (sw, sh) = reader().into_dimensions()?;
if sw as u64 * sh as u64 > MAX_DECODE_PIXELS {
return Err(image::ImageError::Decoding(
image::error::DecodingError::new(
format.into(),
format!(
"{sw}x{sh} is over the {} megapixels a preview decodes",
MAX_DECODE_PIXELS / 1_000_000
),
),
));
}
let img = reader().decode()?;
let scale = f64::min(
canvas_w_px as f64 / sw as f64,
canvas_h_px as f64 / sh as f64,
);
let new_w = ((sw as f64 * scale).round() as u32).max(1);
let new_h = ((sh as f64 * scale).round() as u32).max(1);
let scaled = img
.resize_exact(new_w, new_h, image::imageops::FilterType::Lanczos3)
.to_rgba8();
let mut canvas: RgbaImage = ImageBuffer::from_pixel(canvas_w_px, canvas_h_px, bg);
let off_x = ((canvas_w_px as i64) - (new_w as i64)) / 2;
let off_y = ((canvas_h_px as i64) - (new_h as i64)) / 2;
image::imageops::overlay(&mut canvas, &scaled, off_x, off_y);
let mut out = Vec::with_capacity(8192);
image::DynamicImage::ImageRgba8(canvas)
.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)?;
Ok(out)
}
pub fn cell_source_fraction(
(cell_col, cell_row): (u16, u16),
(cell_w_px, cell_h_px): (u32, u32),
(canvas_w_cells, canvas_h_cells): (u16, u16),
(src_w, src_h): (u32, u32),
) -> Option<(f64, f64, f64, f64)> {
if src_w == 0 || src_h == 0 || cell_col >= canvas_w_cells || cell_row >= canvas_h_cells {
return None;
}
let canvas_w = canvas_w_cells as f64 * cell_w_px as f64;
let canvas_h = canvas_h_cells as f64 * cell_h_px as f64;
let scale = f64::min(canvas_w / src_w as f64, canvas_h / src_h as f64);
let new_w = ((src_w as f64 * scale).round()).max(1.0);
let new_h = ((src_h as f64 * scale).round()).max(1.0);
let off_x = ((canvas_w - new_w) / 2.0).floor();
let off_y = ((canvas_h - new_h) / 2.0).floor();
let x0 = (cell_col as f64 * cell_w_px as f64 - off_x).clamp(0.0, new_w);
let x1 = ((cell_col + 1) as f64 * cell_w_px as f64 - off_x).clamp(0.0, new_w);
let y0 = (cell_row as f64 * cell_h_px as f64 - off_y).clamp(0.0, new_h);
let y1 = ((cell_row + 1) as f64 * cell_h_px as f64 - off_y).clamp(0.0, new_h);
if x1 <= x0 || y1 <= y0 {
return None;
}
Some((x0 / new_w, y0 / new_h, x1 / new_w, y1 / new_h))
}
pub fn build_inline_image_osc(
png: &[u8],
width_cells: u16,
height_cells: u16,
preserve_aspect: bool,
) -> String {
let b64 = base64::engine::general_purpose::STANDARD.encode(png);
let aspect = if preserve_aspect { 1 } else { 0 };
let size = png.len();
format!(
"\x1b]1337;File=inline=1;size={size};width={width_cells};height={height_cells};preserveAspectRatio={aspect}:{b64}\x07"
)
}
pub fn build_inline_image_kitty(
png: &[u8],
width_cells: u16,
height_cells: u16,
image_id: u32,
placement_id: u32,
z: i32,
) -> String {
let b64 = base64::engine::general_purpose::STANDARD.encode(png);
let len = b64.len();
let mut out = String::with_capacity(len + 64);
let mut start = 0usize;
let mut first = true;
let z_field = if z == 0 {
String::new()
} else {
format!(",z={z}")
};
loop {
let end = (start + 4096).min(len);
let more = u8::from(end < len);
if first {
out.push_str(&format!(
"\x1b_Gf=100,a=T,c={width_cells},r={height_cells},C=1,q=2,i={image_id},p={placement_id}{z_field},m={more};"
));
first = false;
} else {
out.push_str(&format!("\x1b_Gm={more};"));
}
out.push_str(&b64[start..end]);
out.push_str("\x1b\\");
start = end;
if start >= len {
break;
}
}
out
}
#[allow(dead_code)]
pub fn delete_kitty_image(image_id: u32) -> String {
format!("\x1b_Ga=d,d=i,i={image_id},q=2\x1b\\")
}
pub fn delete_all_kitty_images() -> String {
"\x1b_Ga=d,d=a,q=2\x1b\\".to_string()
}
pub fn encode_sixel_rgba(rgba: &[u8], width: u32, height: u32) -> String {
let (w, h) = (width as usize, height as usize);
if w == 0 || h == 0 || rgba.len() < w * h * 4 {
return String::new();
}
let nq = color_quant::NeuQuant::new(1, 256, &rgba[..w * h * 4]);
let palette = nq.color_map_rgb(); const ALPHA_CUTOFF: u8 = 128;
let mut indices = vec![0u8; w * h];
let mut opaque = vec![false; w * h];
for i in 0..w * h {
let px = &rgba[i * 4..i * 4 + 4];
if px[3] >= ALPHA_CUTOFF {
opaque[i] = true;
indices[i] = nq.index_of(px) as u8;
}
}
let mut out = String::with_capacity(w * h / 4 + 512);
out.push_str("\x1bP0;1;0q");
out.push_str(&format!("\"1;1;{width};{height}"));
let mut used = [false; 256];
for i in 0..w * h {
if opaque[i] {
used[indices[i] as usize] = true;
}
}
let scale = |v: u8| -> u32 { (v as u32 * 100 + 127) / 255 };
for (c, is_used) in used.iter().enumerate() {
if !is_used {
continue;
}
let (r, g, b) = (palette[c * 3], palette[c * 3 + 1], palette[c * 3 + 2]);
out.push_str(&format!("#{c};2;{};{};{}", scale(r), scale(g), scale(b)));
}
let mut band = 0usize;
while band < h {
let rows = (h - band).min(6);
let mut first_color_in_band = true;
for (c, is_used) in used.iter().enumerate() {
if !is_used {
continue;
}
let mut row: Vec<u8> = Vec::with_capacity(w);
let mut any = false;
for x in 0..w {
let mut bits = 0u8;
for r in 0..rows {
let p = (band + r) * w + x;
if opaque[p] && indices[p] as usize == c {
bits |= 1 << r;
}
}
if bits != 0 {
any = true;
}
row.push(0x3F + bits);
}
if !any {
continue; }
if !first_color_in_band {
out.push('$'); }
first_color_in_band = false;
out.push_str(&format!("#{c}"));
let mut x = 0usize;
while x < w {
let ch = row[x];
let mut run = 1usize;
while x + run < w && row[x + run] == ch {
run += 1;
}
if run >= 4 {
out.push_str(&format!("!{run}"));
out.push(ch as char);
} else {
for _ in 0..run {
out.push(ch as char);
}
}
x += run;
}
}
out.push('-'); band += 6;
}
out.push_str("\x1b\\"); out
}
pub fn build_inline_image_sixel(png: &[u8]) -> Option<String> {
let img = image::load_from_memory(png).ok()?.to_rgba8();
let (w, h) = (img.width(), img.height());
Some(encode_sixel_rgba(img.as_raw(), w, h))
}
pub fn build_inline_image(
protocol: InlineImageProtocol,
png: &[u8],
width_cells: u16,
height_cells: u16,
preserve_aspect: bool,
id: u32,
) -> Option<String> {
build_inline_image_z(
protocol,
png,
width_cells,
height_cells,
preserve_aspect,
id,
0,
)
}
pub const KITTY_Z_BELOW_TEXT_AND_BG: i32 = -2_000_000_000;
const _: () = assert!(KITTY_Z_BELOW_TEXT_AND_BG < -1_073_741_824);
pub fn build_inline_image_z(
protocol: InlineImageProtocol,
png: &[u8],
width_cells: u16,
height_cells: u16,
preserve_aspect: bool,
id: u32,
z: i32,
) -> Option<String> {
match protocol {
InlineImageProtocol::ITerm2 => Some(build_inline_image_osc(
png,
width_cells,
height_cells,
preserve_aspect,
)),
InlineImageProtocol::Kitty => Some(build_inline_image_kitty(
png,
width_cells,
height_cells,
id,
id,
z,
)),
InlineImageProtocol::Sixel => build_inline_image_sixel(png),
InlineImageProtocol::None => None,
}
}
pub const KITTY_ID_BASE: u32 = 0x00C0_F700; pub const KITTY_ID_EXPLORER: u32 = KITTY_ID_BASE + 1;
pub const KITTY_ID_SEARCH: u32 = KITTY_ID_BASE + 2;
pub const KITTY_ID_SOURCE_CONTROL: u32 = KITTY_ID_BASE + 3;
pub const KITTY_ID_REMOTE: u32 = KITTY_ID_BASE + 4;
pub const KITTY_ID_RUN_DEBUG_BAR: u32 = KITTY_ID_BASE + 5;
pub const KITTY_ID_SETTINGS: u32 = KITTY_ID_BASE + 6;
pub const KITTY_ID_RUN_DEBUG_PANEL: u32 = KITTY_ID_BASE + 8;
pub const KITTY_ID_HERO: u32 = KITTY_ID_BASE + 9;
pub const KITTY_ID_SSH: u32 = KITTY_ID_BASE + 10;
pub const KITTY_ID_WELCOME: u32 = KITTY_ID_BASE + 11;
pub const KITTY_ID_EDITOR_BASE: u32 = KITTY_ID_BASE + 12;
pub const KITTY_ID_EXTENSIONS: u32 = KITTY_ID_BASE + 14;
pub const KITTY_ID_LAYOUT_SIDEBAR: u32 = KITTY_ID_BASE + 15;
pub const KITTY_ID_LAYOUT_PANEL: u32 = KITTY_ID_BASE + 16;
pub const KITTY_ID_LAYOUT_CUSTOMIZE: u32 = KITTY_ID_BASE + 17;
pub const KITTY_ID_MINIMAP: u32 = KITTY_ID_BASE + 18;
pub const KITTY_ID_SCM_BADGE: u32 = KITTY_ID_BASE + 19;
pub const KITTY_ID_EXPLORER_BADGE: u32 = KITTY_ID_BASE + 20;
pub const KITTY_ID_REMOTE_BADGE: u32 = KITTY_ID_BASE + 21;
pub const KITTY_ID_TESTING: u32 = KITTY_ID_BASE + 22;
pub const KITTY_ID_TESTING_BADGE: u32 = KITTY_ID_BASE + 23;
pub const KITTY_ID_PROBLEMS_BADGE: u32 = KITTY_ID_BASE + 24;
pub const KITTY_ID_TERMINAL: u32 = KITTY_ID_BASE + 25;
pub const KITTY_ID_MARKDOWN: u32 = KITTY_ID_BASE + 26;
pub const KITTY_ID_PLOT: u32 = KITTY_ID_BASE + 27;
pub const KITTY_ID_CODEQL: u32 = KITTY_ID_BASE + 28;
pub const KITTY_ID_SPONSOR: u32 = KITTY_ID_BASE + 29;
pub fn maybe_tmux_wrap(protocol: InlineImageProtocol, is_tmux: bool, raw: String) -> String {
if is_tmux && protocol != InlineImageProtocol::Sixel {
tmux_passthrough_wrap(&raw)
} else {
raw
}
}
pub fn tmux_passthrough_wrap(seq: &str) -> String {
let mut out = String::with_capacity(seq.len() + 8);
out.push_str("\x1bPtmux;");
for ch in seq.chars() {
if ch == '\x1b' {
out.push_str("\x1b\x1b");
} else {
out.push(ch);
}
}
out.push_str("\x1b\\");
out
}
#[cfg(test)]
mod tests {
use super::*;
fn declared_grayscale_png(w: u32, h: u32) -> Vec<u8> {
use std::io::Write as _;
fn chunk(out: &mut Vec<u8>, kind: &[u8], data: &[u8]) {
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
let mut crc = flate2::Crc::new();
crc.update(kind);
crc.update(data);
out.extend_from_slice(kind);
out.extend_from_slice(data);
out.extend_from_slice(&crc.sum().to_be_bytes());
}
let mut ihdr = Vec::new();
ihdr.extend_from_slice(&w.to_be_bytes());
ihdr.extend_from_slice(&h.to_be_bytes());
ihdr.extend_from_slice(&[8, 0, 0, 0, 0]);
let mut z = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best());
z.write_all(&[0]).unwrap();
z.write_all(&vec![0x80; w as usize]).unwrap();
let idat = z.finish().unwrap();
let mut png = b"\x89PNG\r\n\x1a\n".to_vec();
chunk(&mut png, b"IHDR", &ihdr);
chunk(&mut png, b"IDAT", &idat);
chunk(&mut png, b"IEND", &[]);
png
}
#[test]
fn an_image_declaring_more_pixels_than_the_budget_is_refused_before_decoding() {
let bomb = declared_grayscale_png(23_000, 23_000);
assert!(bomb.len() < 1024, "the bomb is tiny: {} bytes", bomb.len());
let err = fit_image_auto(&bomb, 400, 300, Rgba([0, 0, 0, 255]))
.expect_err("must not render")
.to_string();
assert!(err.contains("23000x23000"), "{err}");
assert!(err.contains("megapixels"), "{err}");
}
#[test]
fn an_image_within_the_budget_still_bakes_at_the_canvas_size() {
let src = image::GrayImage::from_pixel(200, 100, image::Luma([0x80]));
let mut png = Vec::new();
image::DynamicImage::ImageLuma8(src)
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let baked = fit_image_auto(&png, 400, 400, Rgba([0, 0, 0, 255])).unwrap();
let img = image::load_from_memory(&baked).unwrap().to_rgba8();
assert_eq!(img.dimensions(), (400, 400));
assert_eq!(
img.get_pixel(200, 200).0,
[0x80, 0x80, 0x80, 255],
"the picture"
);
assert_eq!(img.get_pixel(200, 10).0, [0, 0, 0, 255], "the letterbox");
}
#[test]
fn iterm_app_is_iterm2() {
assert!(is_iterm2_term_program(Some("iTerm.app")));
}
#[test]
fn fit_image_with_ink_darkens_only_the_white_glyphs() {
let mut src = RgbaImage::new(2, 1);
src.put_pixel(0, 0, Rgba([0xff, 0xff, 0xff, 0xff]));
src.put_pixel(1, 0, Rgba([0xe9, 0x7c, 0x41, 0xff]));
let mut png = Vec::new();
image::DynamicImage::ImageRgba8(src)
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let bg = Rgba([0xff, 0xff, 0xff, 0xff]);
let baked = fit_image_with_ink(&png, 2, 1, bg, Some((0x3b, 0x3b, 0x3b))).unwrap();
let out = image::load_from_memory(&baked).unwrap().to_rgba8();
let white_side = out.get_pixel(0, 0);
let orange_side = out.get_pixel(1, 0);
assert!(
white_side.0[0] < 0x80 && white_side.0[1] < 0x80,
"the white glyph pixel must take the dark ink, got {white_side:?}"
);
assert!(
orange_side.0[0] > 0xc0 && orange_side.0[2] < 0x80,
"the orange stroke must pass through untouched, got {orange_side:?}"
);
assert_eq!(
fit_image_with_ink(&png, 2, 1, bg, None).unwrap(),
fit_image(&png, 2, 1, bg).unwrap()
);
}
#[test]
fn kitty_image_ids_are_pairwise_distinct() {
let ids = [
("EXPLORER", KITTY_ID_EXPLORER),
("SEARCH", KITTY_ID_SEARCH),
("SOURCE_CONTROL", KITTY_ID_SOURCE_CONTROL),
("REMOTE", KITTY_ID_REMOTE),
("RUN_DEBUG_BAR", KITTY_ID_RUN_DEBUG_BAR),
("SETTINGS", KITTY_ID_SETTINGS),
("RUN_DEBUG_PANEL", KITTY_ID_RUN_DEBUG_PANEL),
("HERO", KITTY_ID_HERO),
("SSH", KITTY_ID_SSH),
("WELCOME", KITTY_ID_WELCOME),
("EDITOR_LEFT", KITTY_ID_EDITOR_BASE),
("EDITOR_RIGHT", KITTY_ID_EDITOR_BASE + 1),
("EXTENSIONS", KITTY_ID_EXTENSIONS),
("PLOT", KITTY_ID_PLOT),
("LAYOUT_SIDEBAR", KITTY_ID_LAYOUT_SIDEBAR),
("LAYOUT_PANEL", KITTY_ID_LAYOUT_PANEL),
("LAYOUT_CUSTOMIZE", KITTY_ID_LAYOUT_CUSTOMIZE),
("MINIMAP", KITTY_ID_MINIMAP),
("TERMINAL", KITTY_ID_TERMINAL),
("MARKDOWN", KITTY_ID_MARKDOWN),
("SCM_BADGE", KITTY_ID_SCM_BADGE),
("EXPLORER_BADGE", KITTY_ID_EXPLORER_BADGE),
("REMOTE_BADGE", KITTY_ID_REMOTE_BADGE),
("TESTING", KITTY_ID_TESTING),
("CODEQL", KITTY_ID_CODEQL),
("SPONSOR", KITTY_ID_SPONSOR),
("TESTING_BADGE", KITTY_ID_TESTING_BADGE),
("PROBLEMS_BADGE", KITTY_ID_PROBLEMS_BADGE),
];
for (i, (an, a)) in ids.iter().enumerate() {
for (bn, b) in &ids[i + 1..] {
assert_ne!(a, b, "{an} and {bn} share Kitty image id {a:#x}");
}
}
}
#[test]
fn count_badge_widens_only_past_two_digits() {
assert_eq!(count_badge_cells_w(1), 2);
assert_eq!(count_badge_cells_w(99), 2);
assert_eq!(count_badge_cells_w(100), 3);
}
#[test]
fn count_badge_renders_pill_and_digits() {
let bg = Rgba([0x20, 0x20, 0x20, 0xff]);
let accent = (0x4e, 0x9a, 0xff);
let png = compose_count_badge(3, 9, 18, accent, bg).expect("badge png");
let img = image::load_from_memory(&png).expect("decode").to_rgba8();
assert_eq!((img.width(), img.height()), (18, 18));
let has = |p: Rgba<u8>| img.pixels().any(|q| *q == p);
assert!(
has(Rgba([accent.0, accent.1, accent.2, 0xff])),
"accent pill"
);
assert!(has(Rgba([0xff, 0xff, 0xff, 0xff])), "white digit");
}
#[test]
fn wezterm_is_iterm2_compatible() {
assert!(is_iterm2_term_program(Some("WezTerm")));
}
#[test]
fn apple_terminal_is_not_iterm2() {
assert!(!is_iterm2_term_program(Some("Apple_Terminal")));
}
#[test]
fn missing_term_program_is_not_iterm2() {
assert!(!is_iterm2_term_program(None));
}
#[test]
fn force_inline_images_accepts_true_values() {
assert!(force_inline_images(Some("1")));
assert!(force_inline_images(Some("true")));
assert!(force_inline_images(Some("yes")));
assert!(!force_inline_images(Some("0")));
assert!(!force_inline_images(None));
}
#[test]
fn osk_env_arms_on_termux_or_explicit_force() {
assert!(osk_env(true, None));
assert!(osk_env(false, Some("1")));
assert!(osk_env(false, Some("true")));
assert!(!osk_env(false, Some("0")));
assert!(!osk_env(false, None));
}
#[test]
fn tmux_env_var_detected() {
assert!(is_tmux_env(None, Some("/tmp/tmux-501/default,1234,0")));
}
#[test]
fn empty_tmux_var_is_not_tmux() {
assert!(!is_tmux_env(None, Some("")));
}
#[test]
fn screen_term_is_tmux_like() {
assert!(is_tmux_env(Some("screen-256color"), None));
}
#[test]
fn xterm_is_not_tmux() {
assert!(!is_tmux_env(Some("xterm-256color"), None));
}
#[test]
fn termux_version_var_detected() {
assert!(is_termux_env(Some("0.118.0"), None));
}
#[test]
fn termux_prefix_detected() {
assert!(is_termux_env(None, Some("/data/data/com.termux/files/usr")));
}
#[test]
fn empty_termux_version_is_not_termux() {
assert!(!is_termux_env(Some(""), None));
}
#[test]
fn non_termux_prefix_is_not_termux() {
assert!(!is_termux_env(None, Some("/usr")));
}
#[test]
fn missing_termux_signals_is_not_termux() {
assert!(!is_termux_env(None, None));
}
#[test]
fn termux_does_not_auto_enable_inline_images() {
assert_eq!(
inline_image_protocol_for(None, None),
InlineImageProtocol::None
);
}
#[test]
fn osc1337_starts_with_iterm2_introducer() {
let seq = build_inline_image_osc(b"PNGDATA", 4, 3, true);
assert!(seq.starts_with("\x1b]1337;File="), "wrong prefix: {seq:?}");
}
#[test]
fn osc1337_terminates_with_bel() {
let seq = build_inline_image_osc(b"PNGDATA", 4, 3, true);
assert!(seq.ends_with('\x07'), "must end with BEL: {seq:?}");
}
#[test]
fn osc1337_carries_inline_flag_and_size_in_cells() {
let seq = build_inline_image_osc(b"PNGDATA", 4, 3, true);
assert!(seq.contains("inline=1"));
assert!(seq.contains("width=4"));
assert!(seq.contains("height=3"));
assert!(seq.contains("preserveAspectRatio=1"));
}
#[test]
fn osc1337_payload_is_base64_encoded_png() {
let seq = build_inline_image_osc(b"PNGDATA", 4, 3, true);
assert!(
seq.contains(":UE5HREFUQQ=="),
"expected base64 payload after colon: {seq:?}"
);
}
#[test]
fn compose_icon_positive_off_y_bias_lowers_the_glyph_and_never_clips() {
let src = {
let img: RgbaImage = ImageBuffer::from_pixel(4, 4, Rgba([0xff, 0xff, 0xff, 0xff]));
let mut buf = Vec::new();
image::DynamicImage::ImageRgba8(img)
.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
.unwrap();
buf
};
let bg = Rgba([0x1e, 0x22, 0x2e, 0xff]);
let content_span = |png: &[u8]| -> (u32, u32) {
let img = image::load_from_memory_with_format(png, image::ImageFormat::Png)
.unwrap()
.to_rgba8();
let (mut top, mut bottom) = (None, None);
for y in 0..img.height() {
let has = (0..img.width()).any(|x| img.get_pixel(x, y).0 != bg.0);
if has {
top.get_or_insert(y);
bottom = Some(y);
}
}
(top.unwrap(), bottom.unwrap())
};
let (canvas_w, canvas_h) = (32u32, 48u32);
let centered =
compose_icon(&src, canvas_w, canvas_h, false, IconInk::default(), bg, 0).unwrap();
let lowered = compose_icon(
&src,
canvas_w,
canvas_h,
false,
IconInk::default(),
bg,
10_000,
)
.unwrap();
let (c_top, c_bottom) = content_span(¢ered);
let (l_top, l_bottom) = content_span(&lowered);
assert!(
l_top > c_top && l_bottom > c_bottom,
"a positive bias must push the glyph downward (centered span {c_top}..={c_bottom}, lowered {l_top}..={l_bottom})"
);
assert!(
l_bottom < canvas_h,
"the glyph must stay inside the canvas: bottom row {l_bottom} exceeds {}",
canvas_h - 1
);
assert_eq!(
l_bottom - l_top,
c_bottom - c_top,
"clamping must preserve the glyph height (no clipping), only shift it"
);
}
#[test]
fn compose_icon_canvas_corners_equal_caller_supplied_bg() {
let src = {
let img: RgbaImage = ImageBuffer::from_pixel(1, 1, Rgba([0, 0, 0, 0]));
let mut buf = Vec::new();
image::DynamicImage::ImageRgba8(img)
.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
.unwrap();
buf
};
let bg = Rgba([0x1e, 0x22, 0x2e, 0xff]);
let baked = compose_icon(&src, 32, 16, false, IconInk::default(), bg, 0).unwrap();
let decoded = image::load_from_memory_with_format(&baked, image::ImageFormat::Png)
.unwrap()
.to_rgba8();
let (w, h) = (decoded.width(), decoded.height());
for (x, y) in [(0, 0), (w - 1, 0), (0, h - 1), (w - 1, h - 1)] {
let px = decoded.get_pixel(x, y).0;
assert_eq!(
(px[0], px[1], px[2], px[3]),
(bg.0[0], bg.0[1], bg.0[2], bg.0[3]),
"corner ({x},{y}) must equal caller bg"
);
}
}
#[test]
fn source_control_activity_bar_icon_is_the_no_repo_hero_png() {
let baked = NO_REPO_HERO_PNG;
let decoded = image::load_from_memory_with_format(baked, image::ImageFormat::Png)
.expect("the shipped source-control PNG must decode")
.to_rgba8();
let (w, h) = (decoded.width(), decoded.height());
assert!(
h > w,
"the asset the user supplied is a portrait Y-fork; if the file gets swapped for a square one the activity-bar render will read squashed"
);
let corner = decoded.get_pixel(0, 0).0;
assert_eq!(
corner[3], 0x00,
"the asset must have a transparent background so compose_icon's bg fill stays clean"
);
}
#[test]
fn compose_icon_preserves_source_aspect_ratio_for_a_portrait_png() {
let bg = Rgba([0x1e, 0x22, 0x2e, 0xff]);
let baked = compose_icon(NO_REPO_HERO_PNG, 32, 16, false, IconInk::default(), bg, 0)
.expect("compose_icon must accept the portrait source-control PNG");
let decoded = image::load_from_memory_with_format(&baked, image::ImageFormat::Png)
.unwrap()
.to_rgba8();
assert_eq!(
(decoded.width(), decoded.height()),
(32, 16),
"canvas dimensions must match the requested size regardless of source aspect"
);
let left_corner = decoded.get_pixel(0, 0).0;
let right_corner = decoded.get_pixel(31, 0).0;
assert_eq!(
left_corner,
[bg[0], bg[1], bg[2], bg[3]],
"a portrait source must leave bar-bg fill on the left of the icon (no squash to fill the square)"
);
assert_eq!(
right_corner,
[bg[0], bg[1], bg[2], bg[3]],
"and on the right too"
);
}
#[test]
fn compose_icon_svg_rasterises_codicon_to_canvas_size() {
let bg = Rgba([0x1e, 0x22, 0x2e, 0xff]);
let baked = compose_icon_svg(
EXPLORER_SRC_SVG,
40,
40,
IconState::Inactive,
IconInk::default(),
bg,
0,
)
.expect("the files codicon SVG must rasterise");
let decoded = image::load_from_memory_with_format(&baked, image::ImageFormat::Png)
.unwrap()
.to_rgba8();
assert_eq!((decoded.width(), decoded.height()), (40, 40));
assert_eq!(
decoded.get_pixel(0, 0).0,
[bg[0], bg[1], bg[2], bg[3]],
"corner must stay bar-bg; the glyph sits centred inside a margin"
);
let glyph_opaque = decoded
.pixels()
.any(|p| p.0 != [bg[0], bg[1], bg[2], bg[3]]);
assert!(
glyph_opaque,
"the rasterised glyph must paint visible pixels"
);
}
#[test]
fn the_sponsor_heart_bakes_in_its_own_ink() {
let bg = Rgba([0, 0, 0, 0xff]);
let pink = (0xdb, 0x61, 0xa2);
let ink = IconInk::new(pink, (0xf7, 0x78, 0xba), (0x4e, 0x9a, 0xff));
let baked = compose_icon_svg(
SPONSOR_HEART_SRC_SVG,
40,
40,
IconState::Inactive,
ink,
bg,
0,
)
.expect("the heart codicon SVG must rasterise");
let decoded = image::load_from_memory_with_format(&baked, image::ImageFormat::Png)
.unwrap()
.to_rgba8();
assert!(
decoded
.pixels()
.any(|p| p.0 == [pink.0, pink.1, pink.2, 0xff]),
"the heart's stroke is painted in its pink"
);
}
#[test]
fn compose_icon_svg_active_paints_the_blue_pill() {
let bg = Rgba([0x1e, 0x22, 0x2e, 0xff]);
let baked = compose_icon_svg(
EXPLORER_SRC_SVG,
40,
40,
IconState::Active,
IconInk::default(),
bg,
0,
)
.unwrap();
let decoded = image::load_from_memory_with_format(&baked, image::ImageFormat::Png)
.unwrap()
.to_rgba8();
let mut saw_pill = false;
for y in 0..40 {
if decoded.get_pixel(0, y).0 == [ACTIVE_PILL[0], ACTIVE_PILL[1], ACTIVE_PILL[2], 0xff] {
saw_pill = true;
break;
}
}
assert!(saw_pill, "active icon must carry the left-edge blue pill");
}
#[test]
fn compose_icon_svg_hovered_brightens_glyph_without_the_pill() {
let bg = Rgba([0x1e, 0x22, 0x2e, 0xff]);
let hovered = compose_icon_svg(
EXPLORER_SRC_SVG,
40,
40,
IconState::Hovered,
IconInk::default(),
bg,
0,
)
.unwrap();
let active = compose_icon_svg(
EXPLORER_SRC_SVG,
40,
40,
IconState::Active,
IconInk::default(),
bg,
0,
)
.unwrap();
let inactive = compose_icon_svg(
EXPLORER_SRC_SVG,
40,
40,
IconState::Inactive,
IconInk::default(),
bg,
0,
)
.unwrap();
let decode = |b: &[u8]| {
image::load_from_memory_with_format(b, image::ImageFormat::Png)
.unwrap()
.to_rgba8()
};
let (hov, inact) = (decode(&hovered), decode(&inactive));
let pill = [ACTIVE_PILL[0], ACTIVE_PILL[1], ACTIVE_PILL[2], 0xff];
assert!(
(0..40).all(|y| hov.get_pixel(0, y).0 != pill),
"hovered icon must not carry the selection pill"
);
assert_ne!(
hovered, inactive,
"hover must visibly brighten the resting glyph"
);
assert_ne!(
hovered, active,
"hover (no pill) must stay distinct from the selected state"
);
assert_eq!((hov.width(), hov.height()), (40, 40));
assert_eq!((inact.width(), inact.height()), (40, 40));
}
#[test]
fn compose_icon_svg_ink_follows_the_bar_background() {
let light = crate::theme::Theme::from_id("light");
let (r, g, b) = light.editor_bg_rgb();
let bar = Rgba([r, g, b, 0xff]);
let ink = IconInk::new(
light.activity_icon_inactive_rgb(),
light.activity_icon_active_rgb(),
light.activity_icon_pill_rgb(),
);
let luma = |p: [u8; 4]| {
0.299 * f32::from(p[0]) + 0.587 * f32::from(p[1]) + 0.114 * f32::from(p[2])
};
for state in [IconState::Inactive, IconState::Hovered, IconState::Active] {
let baked = compose_icon_svg(EXPLORER_SRC_SVG, 40, 40, state, ink, bar, 0).unwrap();
let decoded = image::load_from_memory_with_format(&baked, image::ImageFormat::Png)
.unwrap()
.to_rgba8();
let readable_glyph = decoded
.enumerate_pixels()
.any(|(x, _, p)| x >= 8 && luma(p.0) < 160.0);
assert!(
readable_glyph,
"{state:?} icon must stay readable on a light activity bar"
);
if state == IconState::Active {
let (pr, pg, pb) = light.activity_icon_pill_rgb();
assert!(
(0..40).any(|y| decoded.get_pixel(0, y).0 == [pr, pg, pb, 0xff]),
"the selection bar must carry the theme's activeBorder"
);
}
}
}
#[test]
fn run_debug_src_png_is_192x192_with_visible_bug_and_triangle() {
let decoded =
image::load_from_memory_with_format(RUN_DEBUG_SRC_PNG, image::ImageFormat::Png)
.expect("rsvg-convert output must decode as a PNG")
.to_rgba8();
assert_eq!(decoded.width(), 192);
assert_eq!(decoded.height(), 192);
let bug_body = decoded.get_pixel(40, 124).0;
assert!(
bug_body[3] >= 0xc0,
"bug body fill at (40,124) must be (mostly) opaque; got alpha {} — codicon debug-alt's body sits in the lower-left quadrant of a 192x192 render",
bug_body[3]
);
let triangle_stroke = decoded.get_pixel(48, 32).0;
assert!(
triangle_stroke[3] >= 0xc0,
"play-triangle's left stroke at (48,32) must be (mostly) opaque; got alpha {}",
triangle_stroke[3]
);
let corner = decoded.get_pixel(0, 0).0;
assert_eq!(
corner[3], 0x00,
"outside the silhouette must stay transparent so compose_icon's bg fills it"
);
}
#[test]
fn run_debug_icon_composes_through_icon_pipeline() {
let bg = Rgba([0x1e, 0x22, 0x2e, 0xff]);
let baked = compose_icon(RUN_DEBUG_SRC_PNG, 32, 16, false, IconInk::default(), bg, 0)
.expect("compose_icon must accept the SVG-rasterised run-debug PNG");
let decoded = image::load_from_memory_with_format(&baked, image::ImageFormat::Png)
.unwrap()
.to_rgba8();
assert_eq!((decoded.width(), decoded.height()), (32, 16));
}
#[test]
fn portrait_icon_paints_at_least_as_tall_as_a_square_icon_in_the_same_cell() {
let bg = Rgba([0x1e, 0x22, 0x2e, 0xff]);
let canvas_w = 40u32;
let canvas_h = 40u32;
let baked = compose_icon(
NO_REPO_HERO_PNG,
canvas_w,
canvas_h,
false,
IconInk::default(),
bg,
0,
)
.expect("portrait source must compose into the activity-bar cell");
let decoded = image::load_from_memory_with_format(&baked, image::ImageFormat::Png)
.unwrap()
.to_rgba8();
let opaque_rows: u32 = (0..canvas_h)
.filter(|&y| {
(0..canvas_w).any(|x| {
let p = decoded.get_pixel(x, y).0;
[p[0], p[1], p[2], p[3]] != [bg[0], bg[1], bg[2], bg[3]]
})
})
.count() as u32;
let target_max = (canvas_w.min(canvas_h).saturating_sub(4) * 9 / 10).max(8);
let alpha_edge_slack = 2;
assert!(
opaque_rows + alpha_edge_slack >= target_max,
"portrait icon painted {} rows in a {}x{} cell; expected close to target_max ({}) (within {} rows of slack for the Lanczos alpha edges) so it visually matches the square sibling icons",
opaque_rows,
canvas_w,
canvas_h,
target_max,
alpha_edge_slack
);
}
#[test]
fn tmux_passthrough_wrap_doubles_inner_escapes() {
let inner = "\x1b]1337;File=inline=1:DATA\x07";
let wrapped = tmux_passthrough_wrap(inner);
assert!(wrapped.starts_with("\x1bPtmux;"), "DCS prefix");
assert!(wrapped.ends_with("\x1b\\"), "ST terminator");
assert!(
wrapped.contains("\x1b\x1b]1337"),
"inner ESC must be doubled"
);
}
#[test]
fn kitty_graphics_starts_with_apc_introducer() {
let seq = build_inline_image_kitty(b"PNGDATA", 4, 3, 7, 7, 0);
assert!(seq.starts_with("\x1b_G"), "wrong prefix: {seq:?}");
}
#[test]
fn kitty_graphics_terminates_with_st() {
let seq = build_inline_image_kitty(b"PNGDATA", 4, 3, 7, 7, 0);
assert!(seq.ends_with("\x1b\\"), "must end with ST: {seq:?}");
}
#[test]
fn kitty_first_chunk_carries_png_format_action_and_cells() {
let seq = build_inline_image_kitty(b"PNGDATA", 4, 3, 7, 7, 0);
assert!(seq.contains("f=100"), "PNG format: {seq:?}");
assert!(seq.contains("a=T"), "transmit+display: {seq:?}");
assert!(seq.contains("c=4"), "width in cells: {seq:?}");
assert!(seq.contains("r=3"), "height in cells: {seq:?}");
assert!(seq.contains("i=7"), "image id: {seq:?}");
}
#[test]
fn kitty_omits_z_when_zero_but_emits_deep_negative_for_below_text() {
let above = build_inline_image_kitty(b"PNGDATA", 4, 3, 7, 7, 0);
assert!(!above.contains("z="), "no z field when z=0: {above:?}");
let below = build_inline_image_kitty(b"PNGDATA", 4, 3, 7, 7, KITTY_Z_BELOW_TEXT_AND_BG);
assert!(
below.contains(&format!("z={KITTY_Z_BELOW_TEXT_AND_BG}")),
"deep-negative z must be present: {below:?}"
);
}
#[test]
fn kitty_first_chunk_carries_a_stable_placement_id() {
let seq = build_inline_image_kitty(b"PNGDATA", 4, 3, 7, 42, 0);
assert!(
seq.contains("p=42"),
"placement id must be present: {seq:?}"
);
}
#[test]
fn kitty_sets_cursor_and_response_suppression_flags() {
let seq = build_inline_image_kitty(b"PNGDATA", 4, 3, 7, 7, 0);
assert!(seq.contains("C=1"), "cursor must not advance: {seq:?}");
assert!(seq.contains("q=2"), "responses must be suppressed: {seq:?}");
}
#[test]
fn kitty_payload_is_base64_encoded_png() {
let seq = build_inline_image_kitty(b"PNGDATA", 4, 3, 7, 7, 0);
assert!(
seq.contains(";UE5HREFUQQ=="),
"expected base64 payload after the control-data semicolon: {seq:?}"
);
}
#[test]
fn kitty_chunks_payload_larger_than_4096_base64_bytes() {
let png = vec![0xABu8; 4000];
let seq = build_inline_image_kitty(&png, 4, 3, 7, 7, 0);
let chunks: Vec<&str> = seq.split("\x1b\\").filter(|s| !s.is_empty()).collect();
assert!(
chunks.len() >= 2,
"4000 raw bytes must span >1 chunk, got {}",
chunks.len()
);
assert!(
chunks[0].contains("m=1") && chunks[0].contains("f=100"),
"first chunk carries full control data and m=1: {:?}",
chunks[0]
);
assert!(
chunks.last().unwrap().contains("m=0"),
"final chunk must carry m=0: {:?}",
chunks.last().unwrap()
);
for mid in &chunks[1..chunks.len() - 1] {
assert!(
mid.contains("m=1") && !mid.contains("f=100"),
"middle chunks carry only m=, no repeated control data: {mid:?}"
);
}
}
#[test]
fn iterm2_and_wezterm_speak_the_iterm2_protocol() {
assert_eq!(
inline_image_protocol_for(Some("iTerm.app"), None),
InlineImageProtocol::ITerm2
);
assert_eq!(
inline_image_protocol_for(Some("WezTerm"), None),
InlineImageProtocol::ITerm2
);
}
#[test]
fn ghostty_speaks_the_kitty_protocol_not_iterm2() {
assert_eq!(
inline_image_protocol_for(Some("ghostty"), None),
InlineImageProtocol::Kitty
);
}
#[test]
fn kitty_term_is_detected_via_term_env() {
assert_eq!(
inline_image_protocol_for(None, Some("xterm-kitty")),
InlineImageProtocol::Kitty
);
}
#[test]
fn ghostty_term_is_detected_via_term_env_over_ssh() {
assert_eq!(
inline_image_protocol_for(None, Some("xterm-ghostty")),
InlineImageProtocol::Kitty
);
}
#[test]
fn apple_terminal_and_unknown_have_no_inline_protocol() {
assert_eq!(
inline_image_protocol_for(Some("Apple_Terminal"), Some("xterm-256color")),
InlineImageProtocol::None
);
assert_eq!(
inline_image_protocol_for(None, None),
InlineImageProtocol::None
);
}
#[test]
fn a_croft_pane_draws_osc_1337_only_when_its_croft_shows_images() {
assert_eq!(
inline_image_protocol_in(Some("croft"), Some("xterm-256color"), Some("1")),
InlineImageProtocol::ITerm2
);
for gate in [Some("0"), None, Some("")] {
assert_eq!(
inline_image_protocol_in(Some("croft"), Some("xterm-256color"), gate),
InlineImageProtocol::None,
"{gate:?}"
);
}
assert_eq!(
inline_image_protocol_in(Some("ghostty"), Some("xterm-256color"), Some("0")),
InlineImageProtocol::Kitty
);
assert_eq!(
inline_image_protocol_in(Some("Apple_Terminal"), None, Some("1")),
InlineImageProtocol::None
);
}
#[test]
fn switch_warning_fires_only_for_imageless_non_termux_terminals() {
assert!(terminal_warrants_switch_warning(
InlineImageProtocol::None,
false
));
assert!(!terminal_warrants_switch_warning(
InlineImageProtocol::ITerm2,
false
));
assert!(!terminal_warrants_switch_warning(
InlineImageProtocol::Kitty,
false
));
assert!(!terminal_warrants_switch_warning(
InlineImageProtocol::Sixel,
false
));
assert!(!terminal_warrants_switch_warning(
InlineImageProtocol::None,
true
));
}
#[test]
fn da1_sixel_attribute_is_detected_as_standalone_token() {
assert!(da1_advertises_sixel(b"\x1b[?62;1;4;6;9;15c"));
assert!(da1_advertises_sixel(b"\x1b[?62;4c"));
assert!(da1_advertises_sixel(b"\x1b[?4;6c"));
}
#[test]
fn da1_without_sixel_is_rejected() {
assert!(!da1_advertises_sixel(b"\x1b[?1;2c"));
assert!(!da1_advertises_sixel(b"\x1b[?62;14;64c"));
assert!(!da1_advertises_sixel(b""));
assert!(!da1_advertises_sixel(b"hello"));
}
#[test]
fn encode_sixel_wraps_in_dcs_and_declares_palette() {
let rgba = [255u8, 0, 0, 255].repeat(4);
let seq = encode_sixel_rgba(&rgba, 2, 2);
assert!(seq.starts_with("\x1bP0;1;0q"), "DCS sixel intro: {seq:?}");
assert!(seq.contains("\"1;1;2;2"), "raster attrs: {seq:?}");
assert!(seq.contains('#'), "declares a palette register: {seq:?}");
assert!(seq.ends_with("\x1b\\"), "ST terminator: {seq:?}");
}
#[test]
fn encode_sixel_rejects_degenerate_input() {
assert_eq!(encode_sixel_rgba(&[], 0, 0), "");
assert_eq!(encode_sixel_rgba(&[0, 0, 0, 0], 4, 4), "");
}
#[test]
fn build_inline_image_dispatches_sixel() {
let mut png = Vec::new();
let img: RgbaImage = ImageBuffer::from_pixel(2, 2, Rgba([10, 200, 30, 255]));
image::DynamicImage::ImageRgba8(img)
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let seq = build_inline_image(InlineImageProtocol::Sixel, &png, 2, 2, false, 0)
.expect("sixel dispatch");
assert!(seq.starts_with("\x1bP"), "is a sixel DCS: {seq:?}");
assert!(seq.ends_with("\x1b\\"));
}
#[test]
fn maybe_tmux_wrap_skips_sixel_but_wraps_others() {
let raw = "\x1bPq#0;2;0;0;0-\x1b\\".to_string();
assert_eq!(
maybe_tmux_wrap(InlineImageProtocol::Sixel, true, raw.clone()),
raw
);
let wrapped = maybe_tmux_wrap(InlineImageProtocol::ITerm2, true, raw.clone());
assert!(
wrapped.starts_with("\x1bPtmux;"),
"tmux-wrapped: {wrapped:?}"
);
assert_eq!(
maybe_tmux_wrap(InlineImageProtocol::ITerm2, false, raw.clone()),
raw
);
}
#[test]
fn delete_kitty_image_deletes_by_id_quietly() {
let seq = delete_kitty_image(7);
assert!(seq.starts_with("\x1b_G"), "APC prefix: {seq:?}");
assert!(seq.ends_with("\x1b\\"), "ST terminator: {seq:?}");
assert!(seq.contains("a=d"), "delete action: {seq:?}");
assert!(seq.contains("d=i"), "delete by id selector: {seq:?}");
assert!(seq.contains("i=7"), "target id: {seq:?}");
assert!(seq.contains("q=2"), "delete must be quiet too: {seq:?}");
}
#[test]
fn delete_all_kitty_images_clears_every_placement_quietly() {
let seq = delete_all_kitty_images();
assert!(seq.starts_with("\x1b_G"), "APC prefix: {seq:?}");
assert!(seq.ends_with("\x1b\\"), "ST terminator: {seq:?}");
assert!(seq.contains("a=d"), "delete action: {seq:?}");
assert!(seq.contains("d=a"), "delete-all selector: {seq:?}");
assert!(seq.contains("q=2"), "delete must be quiet too: {seq:?}");
}
#[test]
fn ghostty_is_not_classified_as_iterm2() {
assert!(!is_iterm2_term_program(Some("ghostty")));
}
#[test]
fn build_inline_image_dispatches_on_protocol() {
let osc = build_inline_image(InlineImageProtocol::ITerm2, b"PNGDATA", 4, 3, false, 11)
.expect("iTerm2 must produce a sequence");
assert!(
osc.starts_with("\x1b]1337;File="),
"iTerm2 → OSC-1337: {osc:?}"
);
let kitty = build_inline_image(InlineImageProtocol::Kitty, b"PNGDATA", 4, 3, false, 11)
.expect("Kitty must produce a sequence");
assert!(
kitty.starts_with("\x1b_G"),
"Kitty → APC graphics: {kitty:?}"
);
assert!(
kitty.contains("i=11") && kitty.contains("p=11"),
"Kitty uses the id for both image and placement: {kitty:?}"
);
assert!(
build_inline_image(InlineImageProtocol::None, b"PNGDATA", 4, 3, false, 11).is_none(),
"no inline protocol → no sequence"
);
}
#[test]
fn cell_source_fraction_inverts_the_fit_placement() {
assert_eq!(
cell_source_fraction((0, 10), (10, 20), (100, 40), (500, 200)),
Some((0.0, 0.0, 0.01, 0.05))
);
assert_eq!(
cell_source_fraction((50, 20), (10, 20), (100, 40), (500, 200)),
Some((0.5, 0.5, 0.51, 0.55))
);
assert_eq!(
cell_source_fraction((0, 0), (10, 20), (100, 40), (500, 200)),
None
);
assert_eq!(
cell_source_fraction((0, 9), (10, 20), (100, 40), (500, 200)),
None
);
assert_eq!(
cell_source_fraction((0, 7), (10, 20), (100, 40), (500, 250)),
Some((0.0, 0.0, 0.01, 0.02))
);
}
}