use std::cell::Cell;
use std::collections::{HashMap, HashSet};
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
use anyhow::Result;
use image::imageops::FilterType;
use image::{DynamicImage, RgbaImage};
use ratatui::Frame;
use ratatui::buffer::Buffer;
use ratatui::layout::{Rect, Size};
use ratatui::widgets::Widget;
use ratatui_image::picker::cap_parser::Parser;
use ratatui_image::picker::{Capability, Picker, ProtocolType};
use ratatui_image::protocol::kitty::Kitty;
use ratatui_image::sliced::{SignedPosition, SlicedImage, SlicedProtocol};
use ratatui_image::{FontSize, Resize};
use tokio::sync::mpsc::UnboundedSender;
use crate::chats::ChatPhoto;
use crate::lang;
use crate::messages::Preview;
use crate::term::{self, Terminal};
use crate::tg::Tg;
const RESIZE: Resize = Resize::Scale(Some(FilterType::Triangle));
const MAX_AVATARS: usize = 300;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Key {
pub file_id: i32,
pub cols: u16,
pub rows: u16,
pub thumbnail: bool,
pub avatar: bool,
pub round: bool,
}
fn limits() -> image::Limits {
sized(4096)
}
fn sized(side: u32) -> image::Limits {
let mut limits = image::Limits::default();
limits.max_image_width = Some(side);
limits.max_image_height = Some(side);
limits.max_alloc = Some(128 * 1024 * 1024);
limits
}
const STICKER_SIDE: u32 = 1024;
fn open_sticker(path: &str) -> image::ImageResult<image::DynamicImage> {
open_within(path, sized(STICKER_SIDE))
}
pub fn open_image(path: &str) -> image::ImageResult<image::DynamicImage> {
open_within(path, limits())
}
fn open_within(path: &str, limits: image::Limits) -> image::ImageResult<image::DynamicImage> {
let mut reader = image::ImageReader::open(path)?.with_guessed_format()?;
reader.limits(limits);
reader.decode()
}
const YOUR_SIDES: u32 = crate::attach::PHOTO_MAX_SIDES;
pub fn open_photo(path: &str, tdlib_dirs: &[PathBuf]) -> image::ImageResult<DynamicImage> {
match from_this_computer(path, tdlib_dirs) {
Some(resolved) => open_your_image(&resolved),
None => open_image(path),
}
}
fn open_your_image(path: &Path) -> image::ImageResult<DynamicImage> {
use image::ImageDecoder;
let mut limits = sized(YOUR_SIDES);
let mut reader = image::ImageReader::open(path)?.with_guessed_format()?;
reader.limits(limits.clone());
let decoder = reader.into_decoder()?;
let (width, height) = decoder.dimensions();
if width.saturating_add(height) > YOUR_SIDES {
return Err(image::ImageError::Limits(
image::error::LimitError::from_kind(image::error::LimitErrorKind::DimensionError),
));
}
limits.reserve(decoder.total_bytes())?;
DynamicImage::from_decoder(decoder)
}
fn from_this_computer(path: &str, tdlib_dirs: &[PathBuf]) -> Option<PathBuf> {
if tdlib_dirs.is_empty() || crate::attach::on_another_machine(Path::new(path)) {
return None;
}
let path = std::fs::canonicalize(path).ok()?;
let outside = |dir: &PathBuf| match std::fs::canonicalize(dir) {
Ok(dir) => !path.starts_with(dir),
Err(e) => e.kind() == std::io::ErrorKind::NotFound && !path.starts_with(dir),
};
tdlib_dirs.iter().all(outside).then_some(path)
}
const MAX_BUILDING: usize = 4;
const MAX_READY: usize = 200;
const LARGE_CELLS: u32 = 40 * 16;
const MAX_LARGE: usize = 4;
fn large(key: &Key) -> bool {
u32::from(key.cols) * u32::from(key.rows) > LARGE_CELLS
}
const KITTY_BUDGET: usize = 160_000_000;
type Dropped = Arc<Mutex<Vec<u32>>>;
struct KittyImage {
id: u32,
bytes: usize,
dropped: Dropped,
}
impl Drop for KittyImage {
fn drop(&mut self) {
self.dropped
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push(self.id);
}
}
struct Encoded {
image: SlicedProtocol,
kitty: Option<KittyImage>,
}
impl Encoded {
fn kitty_bytes(&self) -> usize {
self.kitty.as_ref().map_or(0, |k| k.bytes)
}
}
fn encode(
picker: &Picker,
image: DynamicImage,
size: Size,
kitty: Option<(u32, Dropped)>,
) -> Result<Encoded> {
let Some((id, dropped)) = kitty else {
let image = SlicedProtocol::new_with_resize(picker, image, size, RESIZE)?;
return Ok(Encoded { image, kitty: None });
};
let font = picker.font_size();
let size = RESIZE.size_for(&image, font, size);
let image = RESIZE.resize(&image, font, size, None);
let bytes = image.width() as usize * image.height() as usize * 4;
let compress = picker
.capabilities()
.contains(&Capability::KittyCompression);
let image = Kitty::new(image, size, id, picker.tmux_detected(), compress)?;
Ok(Encoded {
image: SlicedProtocol::Kitty(image),
kitty: Some(KittyImage { id, bytes, dropped }),
})
}
fn kitty_id_base() -> u32 {
use std::hash::{BuildHasher, RandomState};
RandomState::new().hash_one(std::process::id()) as u32
}
pub(crate) const PLACEHOLDER: char = '\u{10EEEE}';
fn transmit_in(cell: &mut ratatui::buffer::Cell) -> Option<String> {
let symbol = cell.symbol();
if !symbol.starts_with('\x1b') {
return None;
}
let at = symbol.rfind(PLACEHOLDER)?;
let (code, placeholder) = (symbol[..at].to_string(), symbol[at..].to_string());
cell.set_symbol(&placeholder);
Some(code)
}
fn kitty_delete(id: u32, tmux: bool) -> String {
let (start, escape, end) = Parser::tmux_start_escape_end(tmux);
format!("{start}{escape}_Ga=d,d=I,i={id},q=2{escape}\\{end}")
}
thread_local! {
static DECODING: Cell<bool> = const { Cell::new(false) };
}
pub fn panic_is_contained() -> bool {
DECODING.with(Cell::get)
}
pub fn contained<T>(decode: impl FnOnce() -> Result<T>) -> Result<T> {
DECODING.with(|d| d.set(true));
let result = catch_unwind(AssertUnwindSafe(decode))
.unwrap_or_else(|_| Err(anyhow::anyhow!(lang::t("the image couldn't be decoded"))));
DECODING.with(|d| d.set(false));
result
}
const BUILD_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);
fn decode_bytes(data: &[u8]) -> image::ImageResult<image::DynamicImage> {
let mut reader = image::ImageReader::new(std::io::Cursor::new(data)).with_guessed_format()?;
reader.limits(limits());
reader.decode()
}
pub fn circle(photo: &DynamicImage, width: u32, height: u32) -> RgbaImage {
let mut canvas = RgbaImage::new(width, height);
let size = width.min(height);
let side = photo.width().min(photo.height());
if size == 0 || side == 0 {
return canvas;
}
let square = photo
.crop_imm(
(photo.width() - side) / 2,
(photo.height() - side) / 2,
side,
side,
)
.resize_exact(size, size, FilterType::Triangle)
.to_rgba8();
let (left, top) = ((width - size) / 2, (height - size) / 2);
let radius = size as f32 / 2.0;
for (x, y, pixel) in square.enumerate_pixels() {
let dx = x as f32 + 0.5 - radius;
let dy = y as f32 + 0.5 - radius;
let inside = (radius - (dx * dx + dy * dy).sqrt() + 0.5).clamp(0.0, 1.0);
let mut pixel = *pixel;
pixel[3] = (f32::from(pixel[3]) * inside).round() as u8;
canvas.put_pixel(left + x, top + y, pixel);
}
canvas
}
pub struct ImageEvent {
key: Key,
generation: u64,
result: Result<(Encoded, (u32, u32))>,
}
enum FileState {
Downloading,
Ready(String),
Failed,
}
struct Avatar {
image: Encoded,
used: u64,
}
const CELL_CHANGE: u32 = 16;
pub fn measure_cells() -> Option<FontSize> {
let size = crossterm::terminal::window_size().ok()?;
if size.columns == 0 || size.rows == 0 || size.width == 0 || size.height == 0 {
return None;
}
Some(FontSize::new(
size.width / size.columns,
size.height / size.rows,
))
}
fn cells_now(queried: FontSize, then: FontSize, now: FontSize) -> FontSize {
let changed =
|then: u16, now: u16| u32::from(then.abs_diff(now)) * CELL_CHANGE > u32::from(then);
if !changed(then.width, now.width) && !changed(then.height, now.height) {
return queried;
}
let scale = |queried: u16, then: u16, now: u16| {
let (queried, then, now) = (u32::from(queried), u32::from(then.max(1)), u32::from(now));
((queried * now + then / 2) / then).clamp(1, u32::from(u16::MAX)) as u16
};
FontSize::new(
scale(queried.width, then.width, now.width),
scale(queried.height, then.height, now.height),
)
}
pub struct Images {
picker: Picker,
queried: FontSize,
measured: Option<FontSize>,
tx: UnboundedSender<ImageEvent>,
ready: HashMap<Key, (Encoded, u64)>,
frame: u64,
generation: u64,
avatars: HashMap<Key, Avatar>,
avatar_clock: u64,
building: HashMap<(u64, Key), std::time::Instant>,
failed: HashSet<Key>,
files: HashMap<i32, FileState>,
tdlib_dirs: Arc<[PathBuf]>,
pixels: HashMap<i32, (u32, u32)>,
wanted: Vec<(Preview, u16, u16, bool)>,
wanted_avatars: Vec<(ChatPhoto, u16, u16)>,
kitty_id: u32,
dropped: Dropped,
kitty_budget: usize,
transmits: Vec<String>,
untransmitted: Vec<Key>,
}
impl Images {
pub fn new(picker: Picker, tx: UnboundedSender<ImageEvent>) -> Self {
Self {
queried: picker.font_size(),
measured: None,
picker,
tx,
ready: HashMap::new(),
frame: 0,
generation: 0,
avatars: HashMap::new(),
avatar_clock: 0,
building: HashMap::new(),
failed: HashSet::new(),
files: HashMap::new(),
tdlib_dirs: Arc::new([]),
pixels: HashMap::new(),
wanted: Vec::new(),
wanted_avatars: Vec::new(),
kitty_id: kitty_id_base(),
dropped: Dropped::default(),
kitty_budget: KITTY_BUDGET,
transmits: Vec::new(),
untransmitted: Vec::new(),
}
}
pub fn draws_photos(&self) -> bool {
self.picker.protocol_type() != ProtocolType::Halfblocks
}
pub fn paints_over(&self) -> bool {
matches!(
self.picker.protocol_type(),
ProtocolType::Sixel | ProtocolType::Iterm2
)
}
pub fn font_size(&self) -> FontSize {
self.picker.font_size()
}
pub fn kitty(&self) -> bool {
self.picker.protocol_type() == ProtocolType::Kitty
}
pub fn tmux(&self) -> bool {
self.picker.tmux_detected()
}
pub fn measured(&mut self, now: Option<FontSize>) -> bool {
let Some(now) = now else {
return false;
};
let Some(then) = self.measured else {
self.measured = Some(now);
return false;
};
let font = cells_now(self.queried, then, now);
let old = self.picker.font_size();
if (font.width, font.height) == (old.width, old.height) {
return false;
}
let protocol = self.picker.protocol_type();
#[allow(deprecated)]
let mut picker = Picker::from_fontsize(font);
picker.set_protocol_type(protocol);
self.picker = picker;
self.generation += 1;
self.drop_all();
true
}
pub fn get(
&mut self,
photo: &Preview,
cols: u16,
rows: u16,
round: bool,
) -> Option<&SlicedProtocol> {
let key = |thumbnail| Key {
file_id: photo.file_id,
cols,
rows,
thumbnail,
avatar: false,
round,
};
let key = [key(false), key(true)]
.into_iter()
.find(|k| self.ready.contains_key(k))?;
let frame = self.frame;
let (encoded, used) = self.ready.get_mut(&key)?;
*used = frame;
Some(&encoded.image)
}
pub fn sharp(&mut self, photo: &Preview, cols: u16, rows: u16) -> Option<&SlicedProtocol> {
let key = Key {
file_id: photo.file_id,
cols,
rows,
thumbnail: false,
avatar: false,
round: false,
};
let frame = self.frame;
let (encoded, used) = self.ready.get_mut(&key)?;
*used = frame;
Some(&encoded.image)
}
pub fn downloaded(&self, photo: &Preview) -> bool {
matches!(self.files.get(&photo.file_id), Some(FileState::Ready(_)))
}
pub fn is_broken(&self, photo: &Preview) -> bool {
matches!(self.files.get(&photo.file_id), Some(FileState::Failed))
}
pub fn want(&mut self, photo: &Preview, cols: u16, rows: u16, round: bool) {
self.wanted.push((photo.clone(), cols, rows, round));
}
pub fn tdlib_keeps_files_in(&mut self, dirs: Arc<[PathBuf]>) {
self.tdlib_dirs = dirs;
}
pub fn avatar(
&mut self,
photo: &ChatPhoto,
cols: u16,
rows: u16,
covered: bool,
) -> Option<&SlicedProtocol> {
let key = |thumbnail| Key {
file_id: photo.file_id,
cols,
rows,
thumbnail,
avatar: true,
round: false,
};
if covered && self.paints_over() {
return None;
}
let key = [key(false), key(true)]
.into_iter()
.find(|k| self.avatars.contains_key(k))?;
self.avatar_clock += 1;
let avatar = self.avatars.get_mut(&key)?;
avatar.used = self.avatar_clock;
Some(&avatar.image.image)
}
pub fn want_avatar(&mut self, photo: &ChatPhoto, cols: u16, rows: u16) {
self.wanted_avatars.push((photo.clone(), cols, rows));
}
pub fn fetch(&mut self, tg: &Tg) {
self.frame += 1;
self.fetch_avatars(tg);
let font = self.picker.font_size();
for (photo, cols, rows, round) in std::mem::take(&mut self.wanted) {
let full = Key {
file_id: photo.file_id,
cols,
rows,
thumbnail: false,
avatar: false,
round,
};
if self.ready.contains_key(&full) {
continue;
}
let (width, height) = (
u32::from(cols) * u32::from(font.width),
u32::from(rows) * u32::from(font.height),
);
match self.files.get(&photo.file_id) {
Some(FileState::Ready(path)) => {
let path = path.clone();
let (sticker, tdlib_dirs) = (photo.sticker, Arc::clone(&self.tdlib_dirs));
self.build(full, move || match (sticker, round) {
(true, _) => Ok(open_sticker(&path)?),
(false, true) => {
Ok(circle(&open_photo(&path, &tdlib_dirs)?, width, height).into())
}
(false, false) => Ok(open_photo(&path, &tdlib_dirs)?),
});
}
Some(FileState::Downloading | FileState::Failed) => {}
None => {
self.files.insert(photo.file_id, FileState::Downloading);
tg.download(photo.file_id);
}
}
if let Some(data) = photo.thumbnail {
let key = Key {
thumbnail: true,
..full
};
self.build(key, move || match round {
true => Ok(circle(&decode_bytes(&data)?, width, height).into()),
false => Ok(decode_bytes(&data)?),
});
}
}
}
fn fetch_avatars(&mut self, tg: &Tg) {
let font = self.picker.font_size();
for (photo, cols, rows) in std::mem::take(&mut self.wanted_avatars) {
let full = Key {
file_id: photo.file_id,
cols,
rows,
thumbnail: false,
avatar: true,
round: false,
};
if self.avatars.contains_key(&full) {
continue;
}
let (width, height) = (
u32::from(cols) * u32::from(font.width),
u32::from(rows) * u32::from(font.height),
);
let file = self
.files
.entry(photo.file_id)
.or_insert_with(|| match &photo.path {
Some(path) => FileState::Ready(path.clone()),
None => {
tg.download_quiet(photo.file_id);
FileState::Downloading
}
});
if let FileState::Ready(path) = file {
let path = path.clone();
self.build(full, move || {
Ok(circle(&open_image(&path)?, width, height).into())
});
}
if let Some(data) = photo.thumbnail {
let key = Key {
thumbnail: true,
..full
};
self.build(key, move || {
Ok(circle(&decode_bytes(&data)?, width, height).into())
});
}
}
}
pub fn on_downloaded(&mut self, file_id: i32, path: Option<String>) {
let state = path.map_or(FileState::Failed, FileState::Ready);
self.files.insert(file_id, state);
}
pub fn local_file(&mut self, file_id: i32, path: &str) {
self.files
.entry(file_id)
.or_insert_with(|| FileState::Ready(path.into()));
}
pub fn on_built(&mut self, event: ImageEvent) {
self.building.remove(&(event.generation, event.key));
if event.generation != self.generation {
return;
}
match event.result {
Ok((image, _)) if event.key.avatar => self.add_avatar(event.key, image),
Ok((image, pixels)) => {
if !event.key.thumbnail {
self.pixels.insert(event.key.file_id, pixels);
}
self.add_ready(event.key, image);
}
Err(_) => {
self.failed.insert(event.key);
if !event.key.thumbnail {
self.files.insert(event.key.file_id, FileState::Failed);
}
}
}
}
pub fn measured_photo(&self, photo: &Preview) -> Preview {
let mut photo = photo.clone();
if let Some(&(width, height)) = self.pixels.get(&photo.file_id) {
(photo.width, photo.height) = (width.max(1), height.max(1));
}
photo
}
fn add_ready(&mut self, key: Key, image: Encoded) {
self.ready.remove(&key);
while large(&key)
&& self.ready.keys().filter(|k| large(k)).count() >= MAX_LARGE
&& let Some(oldest) = self.least_used(|k, _| large(k))
{
self.ready.remove(&oldest);
}
if self.ready.len() >= MAX_READY
&& let Some(oldest) = self.least_used(|_, _| true)
{
self.ready.remove(&oldest);
}
let shown = self.frame.saturating_sub(1);
while self.kitty_bytes() + image.kitty_bytes() > self.kitty_budget
&& let Some(oldest) = self
.least_used(|k, used| large(k) && used < shown)
.or_else(|| self.least_used(|_, used| used < shown))
{
self.ready.remove(&oldest);
}
if image.kitty.is_some() {
self.untransmitted.push(key);
}
self.ready.insert(key, (image, self.frame));
}
fn least_used(&self, which: impl Fn(&Key, u64) -> bool) -> Option<Key> {
self.ready
.iter()
.filter(|&(key, &(_, used))| which(key, used))
.min_by_key(|(_, (_, used))| *used)
.map(|(&key, _)| key)
}
fn kitty_bytes(&self) -> usize {
self.ready.values().map(|(e, _)| e.kitty_bytes()).sum()
}
fn add_avatar(&mut self, key: Key, image: Encoded) {
if self.avatars.len() >= MAX_AVATARS
&& let Some(oldest) = self
.avatars
.iter()
.min_by_key(|(_, a)| a.used)
.map(|(&k, _)| k)
{
self.avatars.remove(&oldest);
}
if image.kitty.is_some() {
self.untransmitted.push(key);
}
let avatar = Avatar {
image,
used: self.avatar_clock,
};
self.avatars.insert(key, avatar);
}
pub fn clear(&mut self) {
self.ready.clear();
}
pub fn drop_all(&mut self) {
self.ready.clear();
self.avatars.clear();
self.transmits.clear();
}
pub fn send_deletions(&mut self, terminal: &mut Terminal) {
if let Some(code) = self.deletions() {
let _ = term::send(terminal, [code]);
}
}
pub fn prime_transmits(&mut self, terminal: &mut Terminal) {
let codes = self.pending_transmits();
if !codes.is_empty() {
let _ = term::send(terminal, codes);
}
}
fn pending_transmits(&mut self) -> Vec<String> {
let mut codes = Vec::new();
for key in std::mem::take(&mut self.untransmitted) {
let image = if key.avatar {
self.avatars.get(&key).map(|a| &a.image.image)
} else {
self.ready.get(&key).map(|(e, _)| &e.image)
};
let Some(image) = image else {
continue;
};
let area = Rect::new(0, 0, key.cols.max(1), key.rows.max(1));
let mut buf = Buffer::empty(area);
SlicedImage::new(image, SignedPosition::from((0, 0))).render(area, &mut buf);
'cells: for y in 0..area.height {
for x in 0..area.width {
if let Some(code) = transmit_in(&mut buf[(x, y)]) {
codes.push(code);
break 'cells;
}
}
}
}
codes
}
pub fn draw(
&mut self,
frame: &mut Frame,
area: Rect,
at: SignedPosition,
pick: impl for<'a> FnOnce(&'a mut Images) -> Option<&'a SlicedProtocol>,
) -> bool {
let Some(image) = pick(self) else {
return false;
};
frame.render_widget(SlicedImage::new(image, at), area);
self.take_transmit(frame, area, at);
true
}
fn take_transmit(&mut self, frame: &mut Frame, area: Rect, at: SignedPosition) {
if self.picker.protocol_type() != ProtocolType::Kitty {
return;
}
let buf = frame.buffer_mut();
let shown = area.intersection(buf.area);
let left = area.x.saturating_add(at.x.max(0) as u16).max(shown.left());
let top = area.y.saturating_add(at.y.max(0) as u16).max(shown.top());
for y in top..shown.bottom() {
for x in left..shown.right() {
let cell = &mut buf[(x, y)];
if cell.symbol().rfind(PLACEHOLDER).is_some() {
self.transmits.extend(transmit_in(cell));
return;
}
}
}
}
pub fn send_pictures(&mut self, terminal: &mut Terminal) {
if !self.transmits.is_empty() {
let _ = term::send(terminal, std::mem::take(&mut self.transmits));
}
}
#[cfg(test)]
pub fn sending(&self) -> usize {
self.transmits.len()
}
fn deletions(&mut self) -> Option<String> {
let ids = std::mem::take(&mut *self.dropped.lock().unwrap_or_else(PoisonError::into_inner));
if ids.is_empty() {
return None;
}
let tmux = self.picker.tmux_detected();
Some(ids.into_iter().map(|id| kitty_delete(id, tmux)).collect())
}
pub fn forget_files(&mut self) {
self.generation += 1;
self.drop_all();
self.failed.clear();
self.files.clear();
self.pixels.clear();
self.wanted.clear();
self.wanted_avatars.clear();
}
fn build(
&mut self,
key: Key,
decode: impl FnOnce() -> Result<image::DynamicImage> + Send + 'static,
) {
let built = if key.avatar {
self.avatars.contains_key(&key)
} else {
self.ready.contains_key(&key)
};
let (failed, generation) = (&mut self.failed, self.generation);
self.building.retain(|&(started_in, key), started| {
let alive = started.elapsed() < BUILD_TIMEOUT;
if !alive && started_in == generation {
failed.insert(key);
}
alive
});
if built
|| self.building.contains_key(&(generation, key))
|| self.failed.contains(&key)
|| self.building.len() >= MAX_BUILDING
{
return;
}
self.building
.insert((generation, key), std::time::Instant::now());
let picker = self.picker.clone();
let tx = self.tx.clone();
let kitty = self.next_kitty();
tokio::task::spawn_blocking(move || {
let result = contained(|| {
decode().and_then(|image| {
let pixels = (image.width(), image.height());
let size = Size::new(key.cols, key.rows);
let image = encode(&picker, image, size, kitty)?;
Ok((image, pixels))
})
});
let _ = tx.send(ImageEvent {
key,
generation,
result,
});
});
}
fn next_kitty(&mut self) -> Option<(u32, Dropped)> {
(self.picker.protocol_type() == ProtocolType::Kitty).then(|| {
self.kitty_id = self.kitty_id.wrapping_add(1).max(1);
(self.kitty_id, self.dropped.clone())
})
}
#[cfg(test)]
pub fn insert_ready(&mut self, key: Key, image: image::DynamicImage) {
let size = Size::new(key.cols, key.rows);
let kitty = self.next_kitty();
let image = encode(&self.picker, image, size, kitty).unwrap();
if key.avatar {
self.add_avatar(key, image);
} else {
self.add_ready(key, image);
}
}
}
pub type Thumbnail = Arc<[u8]>;
#[cfg(test)]
mod tests {
use super::*;
fn png(width: u32, height: u32) -> Vec<u8> {
let mut data = std::io::Cursor::new(Vec::new());
image::RgbImage::new(width, height)
.write_to(&mut data, image::ImageFormat::Png)
.unwrap();
data.into_inner()
}
#[test]
fn chat_photos_are_cut_to_a_circle_with_see_through_corners() {
let photo = image::RgbaImage::from_pixel(160, 100, image::Rgba([255, 0, 0, 255])).into();
let round = circle(&photo, 40, 44);
let alpha = |x, y| round.get_pixel(x, y)[3];
assert_eq!(alpha(0, 2), 0, "corner");
assert_eq!(alpha(39, 41), 0, "corner");
assert_eq!(alpha(20, 22), 255, "middle");
assert_eq!(alpha(20, 0), 0, "above the circle: the canvas is taller");
assert_eq!(alpha(1, 22), 255, "the circle reaches the sides");
let edge = alpha(6, 7);
assert!(edge > 0 && edge < 255, "a soft edge: {edge}");
assert_eq!(circle(&photo, 0, 44).dimensions(), (0, 44), "no panic");
}
#[test]
fn only_a_few_window_sized_photos_are_kept() {
let tx = tokio::sync::mpsc::unbounded_channel().0;
let mut images = Images::new(Picker::halfblocks(), tx);
let at = |file_id, cols| Key {
file_id,
cols,
rows: 50,
thumbnail: false,
avatar: false,
round: false,
};
for file_id in 0..10 {
images.insert_ready(at(file_id, 4), image::RgbImage::new(4, 4).into());
images.insert_ready(at(file_id, 200), image::RgbImage::new(4, 4).into());
}
let large = images.ready.keys().filter(|k| k.cols == 200).count();
assert_eq!(large, MAX_LARGE);
let small = images.ready.keys().filter(|k| k.cols == 4).count();
assert_eq!(small, 10, "bubbles' photos aren't touched");
}
fn key(file_id: i32) -> Key {
Key {
file_id,
cols: 4,
rows: 2,
thumbnail: false,
avatar: false,
round: false,
}
}
fn preview(file_id: i32) -> Preview {
Preview {
file_id,
width: 8,
height: 8,
thumbnail: None,
sticker: false,
}
}
#[tokio::test]
async fn a_decoder_panic_marks_the_photo_broken_instead_of_ending_the_app() {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let mut images = Images::new(Picker::halfblocks(), tx);
images.build(key(7), || panic!("a decoder bug"));
images.on_built(rx.recv().await.unwrap());
assert!(images.is_broken(&preview(7)));
assert!(!panic_is_contained(), "only while decoding");
}
#[tokio::test]
async fn an_image_built_for_a_logged_out_session_is_dropped() {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let mut images = Images::new(Picker::halfblocks(), tx);
let (go, wait) = std::sync::mpsc::channel::<()>();
images.build(key(7), move || {
wait.recv().ok();
Ok(DynamicImage::new_rgba8(8, 8))
});
images.forget_files();
go.send(()).unwrap();
images.on_built(rx.recv().await.unwrap());
assert!(
images.get(&preview(7), 4, 2, false).is_none(),
"not the new session's"
);
assert!(!images.is_broken(&preview(7)));
}
fn cells_after(queried: (u16, u16), then: (u16, u16), now: (u16, u16)) -> (u16, u16) {
let font = |(w, h)| FontSize::new(w, h);
let size = cells_now(font(queried), font(then), font(now));
(size.width, size.height)
}
#[test]
fn cells_keep_the_size_the_terminal_answered_unless_they_measure_another() {
assert_eq!(cells_after((20, 40), (20, 40), (20, 40)), (20, 40));
assert_eq!(cells_after((20, 40), (20, 40), (20, 41)), (20, 40));
assert_eq!(cells_after((20, 40), (20, 40), (10, 20)), (10, 20));
assert_eq!(cells_after((10, 20), (10, 20), (20, 40)), (20, 40));
assert_eq!(cells_after((20, 40), (21, 42), (10, 21)), (10, 20));
assert_eq!(cells_after((14, 28), (14, 28), (15, 30)), (15, 30));
}
#[tokio::test]
async fn photos_are_made_again_once_cells_change_size() {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let mut images = Images::new(Picker::halfblocks(), tx);
let start = images.font_size();
let measure = |w, h| Some(FontSize::new(w, h));
assert!(
!images.measured(measure(10, 20)),
"the first is the startup's"
);
assert!(!images.measured(None), "a terminal that doesn't say");
assert!(!images.measured(measure(10, 20)));
images.insert_ready(key(1), DynamicImage::new_rgba8(8, 8));
let (go, wait) = std::sync::mpsc::channel::<()>();
images.build(key(7), move || {
wait.recv().ok();
Ok(DynamicImage::new_rgba8(8, 8))
});
assert!(images.measured(measure(20, 40)));
let font = images.font_size();
assert_eq!(
(font.width, font.height),
(start.width * 2, start.height * 2)
);
assert!(!images.draws_photos(), "the protocol stays");
assert!(images.get(&preview(1), 4, 2, false).is_none(), "made again");
go.send(()).unwrap();
images.on_built(rx.recv().await.unwrap());
assert!(images.get(&preview(7), 4, 2, false).is_none(), "dropped");
assert!(!images.is_broken(&preview(7)));
assert!(!images.measured(measure(20, 40)), "only once");
images.build(key(7), || Ok(DynamicImage::new_rgba8(8, 8)));
images.on_built(rx.recv().await.unwrap());
assert!(
images.get(&preview(7), 4, 2, false).is_some(),
"the new size"
);
}
#[tokio::test]
async fn only_a_few_images_decode_at_once() {
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
let mut images = Images::new(Picker::halfblocks(), tx);
let (go, wait) = std::sync::mpsc::channel::<()>();
let wait = std::sync::Arc::new(std::sync::Mutex::new(wait));
for id in 0..10 {
let wait = wait.clone();
images.build(key(id), move || {
let _ = wait.lock().unwrap().recv();
Ok(DynamicImage::new_rgba8(8, 8))
});
}
assert_eq!(images.building.len(), MAX_BUILDING);
drop(go);
}
#[tokio::test]
async fn decodes_left_over_from_another_cell_size_still_take_their_place() {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let mut images = Images::new(Picker::halfblocks(), tx);
images.measured(Some(FontSize::new(10, 20)));
let (go, wait) = std::sync::mpsc::channel::<()>();
let wait = std::sync::Arc::new(std::sync::Mutex::new(wait));
for id in 0..MAX_BUILDING as i32 {
let wait = wait.clone();
images.build(key(id), move || {
let _ = wait.lock().unwrap().recv();
Ok(DynamicImage::new_rgba8(8, 8))
});
}
assert!(images.measured(Some(FontSize::new(20, 40))));
images.build(key(99), || Ok(DynamicImage::new_rgba8(8, 8)));
assert_eq!(images.building.len(), MAX_BUILDING, "no room yet");
drop(go);
images.on_built(rx.recv().await.unwrap());
images.build(key(99), || Ok(DynamicImage::new_rgba8(8, 8)));
assert!(
images.building.contains_key(&(images.generation, key(99))),
"its turn came once an old one was done"
);
}
#[tokio::test]
async fn a_decode_that_never_finishes_gives_up_its_place() {
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
let mut images = Images::new(Picker::halfblocks(), tx);
for id in 0..MAX_BUILDING as i32 {
let long_ago = std::time::Instant::now() - BUILD_TIMEOUT;
images.building.insert((0, key(id)), long_ago);
}
images.build(key(99), || Ok(DynamicImage::new_rgba8(8, 8)));
assert!(images.building.contains_key(&(0, key(99))), "its turn came");
assert!(
images.failed.contains(&key(0)),
"the stuck one counts as failed"
);
}
#[test]
fn the_photo_cache_keeps_the_ones_drawn_lately() {
let (tx, _rx) = tokio::sync::mpsc::unbounded_channel();
let mut images = Images::new(Picker::halfblocks(), tx);
images.insert_ready(key(0), DynamicImage::new_rgba8(8, 8));
for id in 1..MAX_READY as i32 + 10 {
images.frame += 1;
assert!(
images.get(&preview(0), 4, 2, false).is_some(),
"still drawn"
);
images.insert_ready(key(id), DynamicImage::new_rgba8(8, 8));
}
assert_eq!(images.ready.len(), MAX_READY);
assert!(images.get(&preview(0), 4, 2, false).is_some());
assert!(
images.get(&preview(1), 4, 2, false).is_none(),
"the oldest went"
);
}
#[tokio::test]
async fn a_photo_about_to_be_sent_is_read_from_its_file_not_downloaded() {
let dir = std::env::temp_dir().join(format!("tuigram-local-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("cat.png");
std::fs::write(&path, png(80, 60)).unwrap();
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let mut images = Images::new(Picker::halfblocks(), tx);
let photo = preview(-1);
images.local_file(-1, path.to_str().unwrap());
images.want(&photo, 4, 2, false);
images.fetch(&Tg::detached(tokio::sync::mpsc::unbounded_channel().0));
images.on_built(rx.recv().await.unwrap());
assert!(images.get(&photo, 4, 2, false).is_some());
std::fs::remove_dir_all(&dir).unwrap();
}
#[tokio::test]
async fn a_file_named_as_another_format_decodes_and_says_how_big_it_is() {
let dir = std::env::temp_dir().join(format!("tuigram-misnamed-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("photo.jpg");
std::fs::write(&path, png(80, 60)).unwrap();
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let mut images = Images::new(Picker::halfblocks(), tx);
let photo = preview(3);
let size = |p: Preview| (p.width, p.height);
assert_eq!(
size(images.measured_photo(&photo)),
(8, 8),
"as said, until decoded"
);
images.on_downloaded(3, Some(path.to_str().unwrap().into()));
images.want(&photo, 4, 2, false);
images.fetch(&Tg::detached(tokio::sync::mpsc::unbounded_channel().0));
images.on_built(rx.recv().await.unwrap());
assert!(
images.get(&photo, 4, 2, false).is_some(),
"read by its contents"
);
assert_eq!(size(images.measured_photo(&photo)), (80, 60));
std::fs::remove_dir_all(&dir).unwrap();
}
fn kitty() -> Images {
let mut picker = Picker::halfblocks();
picker.set_protocol_type(ProtocolType::Kitty);
let mut images = Images::new(picker, tokio::sync::mpsc::unbounded_channel().0);
images.kitty_id = 0;
images
}
fn photo() -> DynamicImage {
DynamicImage::new_rgba8(40, 40)
}
fn delete(id: u32) -> String {
format!("\x1b_Ga=d,d=I,i={id},q=2\x1b\\")
}
#[test]
fn a_kitty_terminal_is_told_to_delete_the_photos_dropped_by_the_number_they_were_sent_as() {
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::widgets::Widget;
use ratatui_image::sliced::{SignedPosition, SlicedImage};
let mut images = kitty();
images.insert_ready(key(7), photo());
let mut buf = Buffer::empty(Rect::new(0, 0, 4, 2));
let image = images.get(&preview(7), 4, 2, false).unwrap();
SlicedImage::new(image, SignedPosition::from((0, 0))).render(buf.area, &mut buf);
assert!(buf[(0, 0)].symbol().contains("i=1,a=T"), "sent as 1");
assert_eq!(images.deletions(), None, "nothing dropped yet");
images.clear();
assert_eq!(images.deletions(), Some(delete(1)));
assert_eq!(images.deletions(), None, "told once");
}
#[test]
fn a_kitty_image_is_sent_before_the_frame_drawing_its_placeholders() {
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::widgets::Widget;
use ratatui_image::sliced::{SignedPosition, SlicedImage};
let mut images = kitty();
images.insert_ready(key(7), photo());
let codes = images.pending_transmits();
assert_eq!(codes.len(), 1, "made once, off-screen");
assert!(codes[0].contains("i=1,a=T"), "{codes:?}");
assert!(images.pending_transmits().is_empty(), "sent once");
let image = images.get(&preview(7), 4, 2, false).unwrap();
let mut buf = Buffer::empty(Rect::new(0, 0, 4, 2));
SlicedImage::new(image, SignedPosition::from((0, 0))).render(buf.area, &mut buf);
assert!(!buf[(0, 0)].symbol().starts_with('\x1b'), "no code left");
assert!(buf[(0, 0)].symbol().contains(PLACEHOLDER));
let avatar = Key {
avatar: true,
..key(9)
};
images.insert_ready(avatar, photo());
let codes = images.pending_transmits();
assert_eq!(codes.len(), 1, "{codes:?}");
assert!(codes[0].contains("i=2,a=T"), "{codes:?}");
images.insert_ready(key(8), photo());
images.clear();
assert!(images.pending_transmits().is_empty());
}
#[test]
fn chat_photos_are_deleted_too_once_dropped_and_all_of_them_on_quitting() {
let mut images = kitty();
let avatar = |file_id| Key {
avatar: true,
..key(file_id)
};
for file_id in 0..=MAX_AVATARS as i32 {
images.avatar_clock += 1;
images.insert_ready(avatar(file_id), photo());
}
assert_eq!(images.avatars.len(), MAX_AVATARS);
assert_eq!(images.deletions(), Some(delete(1)), "the oldest");
images.insert_ready(key(1000), photo());
images.drop_all();
let code = images.deletions().unwrap();
assert_eq!(code.matches("a=d").count(), MAX_AVATARS + 1);
assert!(images.avatars.is_empty() && images.ready.is_empty());
}
#[test]
fn photos_kept_for_a_kitty_terminal_stay_under_its_quota_but_not_by_dropping_those_on_screen() {
let mut images = kitty();
images.kitty_budget = 2 * 40 * 40 * 4;
images.insert_ready(key(1), photo());
images.frame = 1;
images.insert_ready(key(2), photo());
images.frame = 3;
assert!(images.get(&preview(2), 4, 2, false).is_some());
images.frame = 4;
images.insert_ready(key(3), photo());
assert!(!images.ready.contains_key(&key(1)), "drawn longest ago");
assert!(images.ready.contains_key(&key(2)) && images.ready.contains_key(&key(3)));
assert_eq!(images.deletions(), Some(delete(1)));
assert!(images.get(&preview(2), 4, 2, false).is_some());
assert!(images.get(&preview(3), 4, 2, false).is_some());
images.frame = 5;
images.insert_ready(key(4), photo());
assert_eq!(images.ready.len(), 3);
assert_eq!(images.deletions(), None);
}
#[test]
fn zooming_in_the_viewer_drops_its_other_sizes_before_the_bubbles_photos() {
let mut images = kitty();
let window = |file_id| Key {
cols: 40,
rows: 17,
..key(file_id)
};
let picture = || DynamicImage::new_rgba8(400, 340);
images.kitty_budget = 2 * 400 * 340 * 4;
images.insert_ready(key(1), photo());
images.frame = 2;
images.insert_ready(window(2), picture());
images.frame = 4;
images.insert_ready(window(3), picture());
assert!(
images.ready.contains_key(&key(1)),
"though drawn longest ago"
);
assert!(!images.ready.contains_key(&window(2)));
assert!(images.ready.contains_key(&window(3)));
}
#[test]
fn a_kitty_images_data_goes_apart_from_the_frame_so_what_covers_it_cant_lose_it() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
use ratatui::widgets::Paragraph;
let mut images = kitty();
images.insert_ready(key(7), photo());
let mut terminal = Terminal::new(TestBackend::new(10, 4)).unwrap();
let (area, at) = (Rect::new(1, 1, 4, 2), SignedPosition::from((0, 0)));
let mut draw = |images: &mut Images| {
terminal
.draw(|frame| {
assert!(images.draw(frame, area, at, |i| i.get(&preview(7), 4, 2, false)));
frame.render_widget(Paragraph::new("popup"), Rect::new(0, 1, 6, 1));
})
.unwrap()
.buffer
.clone()
};
let buf = draw(&mut images);
assert_eq!(images.sending(), 1);
assert!(images.transmits[0].contains("i=1,a=T"), "sent as 1");
assert!(
buf.content().iter().all(|c| !c.symbol().contains('\x1b')),
"nothing of it in the frame"
);
draw(&mut images);
assert_eq!(images.sending(), 1, "sent once");
}
#[test]
fn an_images_code_is_found_where_it_starts_drawing_though_its_corner_is_off_the_screen() {
use ratatui::Terminal;
use ratatui::backend::TestBackend;
let mut images = kitty();
images.insert_ready(key(7), photo());
let mut terminal = Terminal::new(TestBackend::new(10, 4)).unwrap();
let (area, at) = (Rect::new(7, 1, 4, 4), SignedPosition::from((0, -1)));
terminal
.draw(|frame| {
assert!(images.draw(frame, area, at, |i| i.get(&preview(7), 4, 2, false)));
})
.unwrap();
assert_eq!(images.sending(), 1);
}
#[test]
fn inside_tmux_the_code_that_deletes_images_goes_through_it() {
assert_eq!(
kitty_delete(1, true),
"\x1bPtmux;\x1b\x1b_Ga=d,d=I,i=1,q=2\x1b\x1b\\\x1b\\"
);
}
#[test]
fn terminals_that_keep_no_images_are_told_nothing() {
let mut images = Images::new(
Picker::halfblocks(),
tokio::sync::mpsc::unbounded_channel().0,
);
images.insert_ready(key(1), photo());
images.drop_all();
assert_eq!(images.deletions(), None);
}
#[test]
fn images_bigger_than_telegram_sends_are_refused() {
assert!(decode_bytes(&png(512, 512)).is_ok());
let error = decode_bytes(&png(5000, 1)).unwrap_err();
assert!(matches!(error, image::ImageError::Limits(_)), "{error}");
}
async fn shows(path: &std::path::Path, tdlib_dirs: &[PathBuf]) -> bool {
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
let mut images = Images::new(Picker::halfblocks(), tx);
images.tdlib_keeps_files_in(tdlib_dirs.into());
images.on_downloaded(3, Some(path.to_str().unwrap().into()));
images.want(&preview(3), 4, 2, false);
images.fetch(&Tg::detached(tokio::sync::mpsc::unbounded_channel().0));
images.on_built(rx.recv().await.unwrap());
images.sharp(&preview(3), 4, 2).is_some()
}
struct TempDir(PathBuf);
impl TempDir {
fn new(name: &str) -> Self {
let dir = std::env::temp_dir().join(format!("tuigram-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[tokio::test]
async fn a_photo_you_sent_shows_though_wider_than_anyone_elses_may_be() {
let temp = TempDir::new("yours");
let dir = &temp.0;
let tdlib = [dir.join("db"), dir.join("files")];
for folder in &tdlib {
std::fs::create_dir_all(folder).unwrap();
}
let screenshot = dir.join("screenshot.png");
std::fs::write(&screenshot, png(4259, 1567)).unwrap();
assert!(shows(&screenshot, &tdlib).await);
let downloaded = tdlib[1].join("photo.png");
std::fs::copy(&screenshot, &downloaded).unwrap();
assert!(!shows(&downloaded, &tdlib).await, "someone else's");
let too_big = dir.join("too-big.png");
std::fs::write(&too_big, png(9_000, 1_001)).unwrap();
assert!(!shows(&too_big, &tdlib).await);
assert!(!shows(&screenshot, &[]).await);
let unmade = [tdlib[0].clone(), dir.join("not-yet")];
assert!(shows(&screenshot, &unmade).await);
let path = screenshot.to_str().unwrap();
assert!(open_photo(path, &tdlib).is_ok());
let downloaded = downloaded.to_str().unwrap();
assert!(open_photo(downloaded, &tdlib).is_err(), "someone else's");
}
}