318 lines
10 KiB
Rust
318 lines
10 KiB
Rust
use std::io::Cursor;
|
|
|
|
use image::{DynamicImage, GenericImageView, ImageBuffer, ImageFormat, Rgb, Rgba};
|
|
use ratatui::{
|
|
Terminal,
|
|
backend::TestBackend,
|
|
layout::{Rect, Size},
|
|
style::Color,
|
|
widgets::Widget,
|
|
};
|
|
use ratatui_image::picker::ProtocolType;
|
|
use rcom::app::PaneId;
|
|
use rcom::domain::Location;
|
|
use rcom::image_preview::{
|
|
FontMetrics, ImageDetectionGates, ImageEngine, ImagePreviewCache, ImagePreviewError,
|
|
MAX_IMAGE_BYTES, PreparedImage, PreparedImageIdentity, checked_dimensions, decode_static,
|
|
prepare_halfblocks, supported_format,
|
|
};
|
|
use rcom::preview::bounded_read;
|
|
|
|
fn encoded(format: ImageFormat, width: u32, height: u32) -> Vec<u8> {
|
|
let image = DynamicImage::ImageRgb8(ImageBuffer::from_pixel(width, height, Rgb([20, 80, 140])));
|
|
let mut cursor = Cursor::new(Vec::new());
|
|
image.write_to(&mut cursor, format).unwrap();
|
|
cursor.into_inner()
|
|
}
|
|
|
|
#[test]
|
|
fn content_magic_recognizes_exactly_the_five_enabled_formats() {
|
|
for (format, expected) in [
|
|
(ImageFormat::Png, "Png"),
|
|
(ImageFormat::Jpeg, "Jpeg"),
|
|
(ImageFormat::Gif, "Gif"),
|
|
(ImageFormat::Bmp, "Bmp"),
|
|
(ImageFormat::WebP, "WebP"),
|
|
] {
|
|
let bytes = encoded(format, 3, 2);
|
|
assert_eq!(format!("{:?}", supported_format(&bytes).unwrap()), expected);
|
|
let decoded = decode_static(bytes, false).unwrap();
|
|
assert_eq!((decoded.width(), decoded.height()), (3, 2));
|
|
}
|
|
assert!(supported_format(b"plain text").is_none());
|
|
assert!(matches!(
|
|
decode_static(b"not an image".to_vec(), false),
|
|
Err(ImagePreviewError::UnsupportedFormat)
|
|
));
|
|
}
|
|
|
|
#[test]
|
|
fn animated_gif_decodes_to_one_static_first_frame() {
|
|
use image::{Frame, codecs::gif::GifEncoder};
|
|
|
|
let first = ImageBuffer::from_pixel(2, 2, Rgba([255, 0, 0, 255]));
|
|
let second = ImageBuffer::from_pixel(2, 2, Rgba([0, 0, 255, 255]));
|
|
let mut bytes = Vec::new();
|
|
GifEncoder::new(&mut bytes)
|
|
.encode_frames([Frame::new(first), Frame::new(second)])
|
|
.unwrap();
|
|
let decoded = decode_static(bytes, false).unwrap();
|
|
assert_eq!(decoded.dimensions(), (2, 2));
|
|
assert_eq!(decoded.into_rgba8().get_pixel(0, 0).0, [255, 0, 0, 255]);
|
|
}
|
|
|
|
#[test]
|
|
fn corrupt_truncated_and_oversized_inputs_fail_before_rendering() {
|
|
let mut png = encoded(ImageFormat::Png, 4, 4);
|
|
png.truncate(png.len() / 2);
|
|
assert!(decode_static(png.clone(), false).is_err());
|
|
assert!(matches!(
|
|
decode_static(encoded(ImageFormat::Png, 1, 1), true),
|
|
Err(ImagePreviewError::EncodedTooLarge)
|
|
));
|
|
assert!(matches!(
|
|
decode_static(vec![0; MAX_IMAGE_BYTES + 1], false),
|
|
Err(ImagePreviewError::EncodedTooLarge)
|
|
));
|
|
assert!(decode_static(encoded(ImageFormat::Png, MAX_IMAGE_AXIS_PLUS_ONE, 1), false).is_err());
|
|
}
|
|
|
|
const MAX_IMAGE_AXIS_PLUS_ONE: u32 = 8193;
|
|
|
|
#[tokio::test]
|
|
async fn bounded_image_read_distinguishes_exact_cap_and_one_lookahead_byte() {
|
|
let exact = bounded_read(&vec![7; MAX_IMAGE_BYTES][..], MAX_IMAGE_BYTES)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(exact.bytes.len(), MAX_IMAGE_BYTES);
|
|
assert!(!exact.truncated);
|
|
let over = bounded_read(&vec![7; MAX_IMAGE_BYTES + 1][..], MAX_IMAGE_BYTES)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(over.bytes.len(), MAX_IMAGE_BYTES);
|
|
assert!(over.truncated);
|
|
}
|
|
|
|
#[test]
|
|
fn checked_geometry_rejects_zero_overflow_axis_and_pixel_budget() {
|
|
for dimensions in [
|
|
(0, 1),
|
|
(1, 0),
|
|
(8193, 1),
|
|
(1, 8193),
|
|
(u32::MAX, u32::MAX),
|
|
(8000, 4001),
|
|
] {
|
|
assert!(
|
|
checked_dimensions(dimensions.0, dimensions.1).is_err(),
|
|
"{dimensions:?}"
|
|
);
|
|
}
|
|
assert!(checked_dimensions(8192, 1).is_ok());
|
|
assert!(checked_dimensions(8000, 4000).is_ok());
|
|
}
|
|
|
|
#[test]
|
|
fn halfblocks_render_real_known_pixels_without_a_picker_or_terminal_probe() {
|
|
let mut pixels = ImageBuffer::from_pixel(10, 20, Rgba([255, 0, 0, 255]));
|
|
for pixel in pixels.enumerate_pixels_mut() {
|
|
if pixel.1 >= 10 {
|
|
*pixel.2 = Rgba([0, 0, 255, 255]);
|
|
}
|
|
}
|
|
let protocol = prepare_halfblocks(DynamicImage::ImageRgba8(pixels), Size::new(1, 1)).unwrap();
|
|
assert_eq!(protocol.size(), Size::new(1, 1));
|
|
let mut terminal = Terminal::new(TestBackend::new(3, 2)).unwrap();
|
|
terminal
|
|
.draw(|frame| {
|
|
ratatui_image::Image::new(&protocol).render(Rect::new(1, 0, 1, 1), frame.buffer_mut());
|
|
})
|
|
.unwrap();
|
|
let cell = terminal.backend().buffer().cell((1, 0)).unwrap();
|
|
assert_eq!(cell.symbol(), "▀");
|
|
assert_eq!(cell.fg, Color::Rgb(219, 0, 36));
|
|
assert_eq!(cell.bg, Color::Rgb(36, 0, 219));
|
|
assert_eq!(
|
|
terminal.backend().buffer().cell((0, 0)).unwrap().symbol(),
|
|
" "
|
|
);
|
|
assert_eq!(
|
|
terminal.backend().buffer().cell((2, 1)).unwrap().symbol(),
|
|
" "
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn aspect_fit_never_upscales_or_panics_on_wide_tall_tiny_and_zero_areas() {
|
|
for (source, area) in [
|
|
((100, 10), Size::new(4, 4)),
|
|
((10, 100), Size::new(4, 4)),
|
|
((1, 1), Size::new(20, 20)),
|
|
((2, 2), Size::new(1, 1)),
|
|
] {
|
|
let image = DynamicImage::ImageRgb8(ImageBuffer::new(source.0, source.1));
|
|
let protocol = prepare_halfblocks(image, area).unwrap();
|
|
assert!(protocol.size().width <= area.width);
|
|
assert!(protocol.size().height <= area.height);
|
|
}
|
|
let image = DynamicImage::ImageRgb8(ImageBuffer::new(1, 1));
|
|
assert!(matches!(
|
|
prepare_halfblocks(image, Size::new(0, 1)),
|
|
Err(ImagePreviewError::EmptyArea)
|
|
));
|
|
}
|
|
|
|
fn gates() -> ImageDetectionGates {
|
|
ImageDetectionGates {
|
|
images: true,
|
|
colors: true,
|
|
ascii: false,
|
|
dumb: false,
|
|
tty: true,
|
|
tmux: false,
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn disabled_and_tmux_gates_never_invoke_a_picker_or_probe() {
|
|
for mutate in [
|
|
(|gate: &mut ImageDetectionGates| gate.images = false) as fn(&mut _),
|
|
|gate| gate.colors = false,
|
|
|gate| gate.ascii = true,
|
|
|gate| gate.dumb = true,
|
|
|gate| gate.tty = false,
|
|
] {
|
|
let mut gate = gates();
|
|
mutate(&mut gate);
|
|
let engine = ImageEngine::detect_with(gate, || -> Result<_, ()> {
|
|
panic!("disabled mode must not query or construct a picker")
|
|
});
|
|
assert!(engine.factory().is_none());
|
|
}
|
|
let engine = ImageEngine::detect_with(
|
|
ImageDetectionGates {
|
|
tmux: true,
|
|
..gates()
|
|
},
|
|
|| -> Result<_, ()> { panic!("tmux must use direct halfblocks") },
|
|
);
|
|
assert_eq!(
|
|
engine.factory().unwrap().protocol_type(),
|
|
ProtocolType::Halfblocks
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn failed_query_falls_back_once_to_halfblocks() {
|
|
let mut calls = 0;
|
|
let engine = ImageEngine::detect_with(gates(), || -> Result<_, &str> {
|
|
calls += 1;
|
|
Err("timeout")
|
|
});
|
|
assert_eq!(calls, 1);
|
|
assert_eq!(
|
|
engine.factory().unwrap().protocol_type(),
|
|
ProtocolType::Halfblocks
|
|
);
|
|
}
|
|
|
|
fn identity(pane: PaneId, generation: u64) -> PreparedImageIdentity {
|
|
PreparedImageIdentity {
|
|
pane,
|
|
generation,
|
|
target: Location::local(format!("/fixture/{generation}.png")),
|
|
session_epoch: None,
|
|
area: Size::new(1, 1),
|
|
font: FontMetrics {
|
|
width: 10,
|
|
height: 20,
|
|
},
|
|
protocol: ProtocolType::Halfblocks,
|
|
terminal_epoch: 0,
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn native_protocol_factories_produce_bounded_structural_protocols_without_wire_snapshots() {
|
|
if std::env::var_os("TMUX").is_some()
|
|
|| std::env::var("TERM_PROGRAM").is_ok_and(|program| program.eq_ignore_ascii_case("tmux"))
|
|
|| std::env::var("TERM").is_ok_and(|term| term.starts_with("tmux"))
|
|
{
|
|
// Never call an upstream Picker constructor in a tmux test environment.
|
|
return;
|
|
}
|
|
for protocol in [
|
|
ProtocolType::Kitty,
|
|
ProtocolType::Iterm2,
|
|
ProtocolType::Sixel,
|
|
] {
|
|
let mut picker = ratatui_image::picker::Picker::halfblocks();
|
|
picker.set_protocol_type(protocol);
|
|
let factory = rcom::image_preview::ImageProtocolFactory::Picker(picker);
|
|
let prepared = factory
|
|
.prepare(
|
|
DynamicImage::ImageRgba8(ImageBuffer::from_pixel(10, 20, Rgba([1, 2, 3, 255]))),
|
|
Size::new(1, 1),
|
|
)
|
|
.unwrap();
|
|
assert_eq!(prepared.size(), Size::new(1, 1));
|
|
assert!(matches!(
|
|
(protocol, prepared),
|
|
(
|
|
ProtocolType::Kitty,
|
|
ratatui_image::protocol::Protocol::Kitty(_)
|
|
) | (
|
|
ProtocolType::Iterm2,
|
|
ratatui_image::protocol::Protocol::ITerm2(_)
|
|
) | (
|
|
ProtocolType::Sixel,
|
|
ratatui_image::protocol::Protocol::Sixel(_)
|
|
)
|
|
));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn prepared_cache_is_bounded_and_rejects_stale_identity_and_terminal_epochs() {
|
|
let mut cache = ImagePreviewCache::default();
|
|
for pane in [PaneId::Left, PaneId::Right] {
|
|
let id = identity(pane, 1);
|
|
let protocol = prepare_halfblocks(
|
|
DynamicImage::ImageRgb8(ImageBuffer::new(10, 20)),
|
|
Size::new(1, 1),
|
|
)
|
|
.unwrap();
|
|
cache.insert(PreparedImage {
|
|
identity: id.clone(),
|
|
protocol,
|
|
});
|
|
assert!(cache.current(&id).is_some());
|
|
let mut stale = id.clone();
|
|
stale.generation += 1;
|
|
assert!(cache.current(&stale).is_none());
|
|
let mut wrong_geometry = id.clone();
|
|
wrong_geometry.area = Size::new(2, 2);
|
|
assert!(cache.current(&wrong_geometry).is_none());
|
|
let mut wrong_terminal = id;
|
|
wrong_terminal.terminal_epoch = 1;
|
|
assert!(cache.current(&wrong_terminal).is_none());
|
|
}
|
|
assert_eq!(cache.len(), 2);
|
|
let replacement = identity(PaneId::Left, 2);
|
|
let protocol = prepare_halfblocks(
|
|
DynamicImage::ImageRgb8(ImageBuffer::new(10, 20)),
|
|
Size::new(1, 1),
|
|
)
|
|
.unwrap();
|
|
cache.insert(PreparedImage {
|
|
identity: replacement.clone(),
|
|
protocol,
|
|
});
|
|
assert_eq!(cache.len(), 2);
|
|
assert!(cache.current(&identity(PaneId::Left, 1)).is_none());
|
|
assert!(cache.current(&replacement).is_some());
|
|
cache.remove_pane(PaneId::Left);
|
|
assert_eq!(cache.len(), 1);
|
|
cache.clear();
|
|
assert!(cache.is_empty());
|
|
}
|