use matrix_sdk::Media; use matrix_sdk::media::{MediaFormat, MediaRequestParameters, UniqueKey}; use ratatui_image::picker::Picker; use ratatui_image::{FilterType, Resize}; use tokio::sync::Semaphore; use crate::config::ImagePreviewValues; use crate::prelude::*; pub enum ImageStatus { Queued(Size), Downloading(Size), Loaded(Arc), Error(String), } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum PreviewKind { /// A custom `width, height` is given in pixels or defaults to the config Custom(Option, Option), /// Force the image to be rendered in Emoji presentation (i.e., 1x2 characters) /// /// This is used primarily for custom message reactions and for the `data-mx-emoticon` /// attribute on images, which is typically used when forcing stickers to appear like /// custom Emoji. /// /// In the future, we could potentially investigate using this as a way to also handle /// troublesome ZWJ combinations that confuse terminals or ratatui by not having clear /// widths across implementations. Emoji, } impl Default for PreviewKind { fn default() -> Self { Self::Custom(None, None) } } impl PreviewKind { fn image_size(self, picker: &Picker, image_preview: &ImagePreviewValues) -> Size { match self { Self::Emoji => Size { width: 2, height: 1 }, Self::Custom(width, height) => { let font_size = picker.font_size(); let width = width .map(|width| width.div_ceil(font_size.width)) .unwrap_or(image_preview.size.width) .min(image_preview.size.width); let height = height .map(|height| height.div_ceil(font_size.height)) .unwrap_or(image_preview.size.height) .min(image_preview.size.height); Size { width, height } }, } } } pub struct PreviewManager { /// Image preview "protocol" picker. picker: Arc, /// Permits for rendering images in background thread. permits: Arc, /// Indexed by [`MediaSource::unique_key`] previews: HashMap<(String, PreviewKind), ImageStatus>, } impl PreviewManager { pub fn new(settings: &ApplicationSettings) -> Self { let picker = picker_from_settings(settings); Self { picker: picker.into(), permits: Arc::new(Semaphore::new(2)), previews: Default::default(), } } pub fn get(&self, source: &MediaSource, kind: PreviewKind) -> Option<&ImageStatus> { self.previews.get(&(source.unique_key(), kind)) } fn insert(&mut self, key: String, kind: PreviewKind, status: ImageStatus) { self.previews.insert((key, kind), status); } /// Queue download and preparation of preview pub fn load(&mut self, source: &MediaSource, kind: PreviewKind, worker: &Requester) { let Some(status) = self.previews.get_mut(&(source.unique_key(), kind)) else { return; }; if let ImageStatus::Queued(size) = status { let size = *size; *status = ImageStatus::Downloading(size); worker.load_image( source.to_owned(), kind, size.to_owned(), Arc::clone(&self.picker), Arc::clone(&self.permits), ); } } pub fn register_preview( &mut self, settings: &ApplicationSettings, source: &MediaSource, kind: PreviewKind, ) { let key = (source.unique_key(), kind); if self.previews.contains_key(&key) { return; } let size = kind.image_size(&self.picker, &settings.tunables.image_preview); self.previews.insert(key, ImageStatus::Queued(size)); } } fn picker_from_query() -> Picker { // XXX: documentation says to use this query on alternate screen but it seems to be fine Picker::from_query_stdio().unwrap_or_else(|e| { tracing::warn!("Failed to setup image previews (falling back to halfblock rendering): {e}"); Picker::halfblocks() }) } fn picker_from_settings(settings: &ApplicationSettings) -> Picker { let mut picker = if !settings.tunables.image_preview.enabled { // Skip any auto-detection and use halfblocks when disabled: Picker::halfblocks() } else if let Some(font_size) = settings.tunables.image_preview.protocol.font_size { #[expect(deprecated, reason = "from_query_stdio doesn't work on windows")] Picker::from_fontsize(font_size.into()) } else { picker_from_query() }; // user forced protocol type; use that if let Some(protocol_type) = settings.tunables.image_preview.protocol.r#type { picker.set_protocol_type(protocol_type); } picker } pub async fn load_image( store: AsyncProgramStore, media: Media, source: MediaSource, kind: PreviewKind, picker: Arc, permits: Arc, size: Size, ) { async fn load_image_inner( media: Media, source: MediaSource, picker: Arc, permits: Arc, size: Size, filter: FilterType, ) -> Result { let reader = media .get_media_content(&MediaRequestParameters { source, format: MediaFormat::File }, true) .await .map(std::io::Cursor::new) .map(image::ImageReader::new) .map_err(IambError::Matrix) .and_then(|reader| reader.with_guessed_format().map_err(IambError::IOError))?; let permit = permits .acquire() .await .map_err(|err| IambError::Preview(err.to_string()))?; let handle = tokio::task::spawn_blocking(move || { let image = reader.decode().map_err(IambError::Image)?; SlicedProtocol::new_with_resize(&picker, image, size, Resize::Fit(Some(filter))) .map_err(|err| IambError::Preview(err.to_string())) }); let image = handle.await.map_err(|err| IambError::Preview(err.to_string()))??; std::mem::drop(permit); Ok(ImageStatus::Loaded(Arc::new(image))) } let key = source.unique_key(); let filter = store .lock() .await .application .settings .tunables .image_preview .protocol .filter .unwrap_or(FilterType::Triangle); let status = match load_image_inner(media, source, picker, permits, size, filter).await { Ok(status) => status, Err(err) => ImageStatus::Error(format!("{err:?}")), }; let mut locked = store.lock().await; locked.application.previews.insert(key, kind, status); }