src/preview.rs

231 lines · 6758 bytes

  1use std::{collections::HashMap, sync::Arc};
  2
  3use matrix_sdk::{
  4    Media,
  5    media::{MediaFormat, MediaRequestParameters, UniqueKey},
  6    ruma::events::room::MediaSource,
  7};
  8use ratatui::layout::{Rect, Size};
  9use ratatui_image::{FilterType, Resize, picker::Picker, protocol::Protocol};
 10use tokio::sync::Semaphore;
 11
 12use crate::{
 13    base::{AsyncProgramStore, IambError},
 14    config::{ApplicationSettings, ImagePreviewSize, ImagePreviewValues},
 15    worker::Requester,
 16};
 17
 18pub enum ImageStatus {
 19    Queued(ImagePreviewSize),
 20    Downloading(ImagePreviewSize),
 21    Loaded(Protocol),
 22    Error(String),
 23}
 24
 25#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
 26pub enum PreviewKind {
 27    Message,
 28    Reaction,
 29}
 30
 31impl PreviewKind {
 32    fn image_size(self, image_preview: &ImagePreviewValues) -> ImagePreviewSize {
 33        match self {
 34            Self::Message => image_preview.size,
 35            Self::Reaction => ImagePreviewSize { width: 2, height: 1 },
 36        }
 37    }
 38}
 39
 40pub struct PreviewManager {
 41    /// Image preview "protocol" picker.
 42    picker: Arc<Picker>,
 43
 44    /// Permits for rendering images in background thread.
 45    permits: Arc<Semaphore>,
 46
 47    /// Indexed by [`MediaSource::unique_key`]
 48    previews: HashMap<(String, PreviewKind), ImageStatus>,
 49}
 50
 51impl PreviewManager {
 52    pub fn new(settings: &ApplicationSettings) -> Self {
 53        let picker = picker_from_settings(settings);
 54
 55        Self {
 56            picker: picker.into(),
 57            permits: Arc::new(Semaphore::new(2)),
 58            previews: Default::default(),
 59        }
 60    }
 61
 62    pub fn get(&self, source: &MediaSource, kind: PreviewKind) -> Option<&ImageStatus> {
 63        self.previews.get(&(source.unique_key(), kind))
 64    }
 65
 66    fn insert(&mut self, key: String, kind: PreviewKind, status: ImageStatus) {
 67        self.previews.insert((key, kind), status);
 68    }
 69
 70    /// Queue download and preparation of preview
 71    pub fn load(&mut self, source: &MediaSource, kind: PreviewKind, worker: &Requester) {
 72        let Some(status) = self.previews.get_mut(&(source.unique_key(), kind)) else {
 73            return;
 74        };
 75
 76        if let ImageStatus::Queued(size) = status {
 77            let size = *size;
 78            *status = ImageStatus::Downloading(size);
 79
 80            worker.load_image(
 81                source.to_owned(),
 82                kind,
 83                size.to_owned(),
 84                Arc::clone(&self.picker),
 85                Arc::clone(&self.permits),
 86            );
 87        }
 88    }
 89
 90    pub fn register_preview(
 91        &mut self,
 92        settings: &ApplicationSettings,
 93        source: &MediaSource,
 94        kind: PreviewKind,
 95        worker: &Requester,
 96    ) {
 97        let key = (source.unique_key(), kind);
 98        if self.previews.contains_key(&key) {
 99            return;
100        }
101
102        let size = kind.image_size(&settings.tunables.image_preview);
103        self.previews.insert(key, ImageStatus::Queued(size));
104
105        if settings.tunables.image_preview.enabled && !settings.tunables.image_preview.lazy_load {
106            self.load(source, kind, worker);
107        }
108    }
109}
110
111#[cfg(not(windows))]
112fn picker_from_query() -> Picker {
113    // XXX: documentation says to use this query on alternate screen but it seems to be fine
114    Picker::from_query_stdio().unwrap_or_else(|e| {
115        tracing::warn!("Failed to setup image previews (falling back to halfblock rendering): {e}");
116        Picker::halfblocks()
117    })
118}
119
120#[cfg(windows)]
121fn picker_from_query() -> Picker {
122    tracing::error!(
123        "\"image_preview\" requires \"protocol\" with \"type\" and \"font_size\" options on Windows."
124    );
125    Picker::halfblocks()
126}
127
128fn picker_from_settings(settings: &ApplicationSettings) -> Picker {
129    let mut picker = if let Some(font_size) = settings.tunables.image_preview.protocol.font_size {
130        #[expect(deprecated, reason = "from_query_stdio doesn't work on windows")]
131        Picker::from_fontsize(font_size.into())
132    } else {
133        picker_from_query()
134    };
135
136    // user forced protocol type; use that
137    if let Some(protocol_type) = settings.tunables.image_preview.protocol.r#type {
138        picker.set_protocol_type(protocol_type);
139    }
140
141    picker
142}
143
144impl From<ImagePreviewSize> for Rect {
145    fn from(value: ImagePreviewSize) -> Self {
146        Rect::new(0, 0, value.width as _, value.height as _)
147    }
148}
149
150impl From<ImagePreviewSize> for Size {
151    fn from(value: ImagePreviewSize) -> Self {
152        Size::new(value.width as _, value.height as _)
153    }
154}
155
156impl From<Rect> for ImagePreviewSize {
157    fn from(rect: Rect) -> Self {
158        ImagePreviewSize { width: rect.width as _, height: rect.height as _ }
159    }
160}
161
162impl From<Size> for ImagePreviewSize {
163    fn from(size: Size) -> Self {
164        ImagePreviewSize { width: size.width as _, height: size.height as _ }
165    }
166}
167
168pub async fn load_image(
169    store: AsyncProgramStore,
170    media: Media,
171    source: MediaSource,
172    kind: PreviewKind,
173    picker: Arc<Picker>,
174    permits: Arc<Semaphore>,
175    size: ImagePreviewSize,
176) {
177    async fn load_image_inner(
178        media: Media,
179        source: MediaSource,
180        picker: Arc<Picker>,
181        permits: Arc<Semaphore>,
182        size: ImagePreviewSize,
183        filter: FilterType,
184    ) -> Result<ImageStatus, IambError> {
185        let reader = media
186            .get_media_content(&MediaRequestParameters { source, format: MediaFormat::File }, true)
187            .await
188            .map(std::io::Cursor::new)
189            .map(image::ImageReader::new)
190            .map_err(IambError::Matrix)
191            .and_then(|reader| reader.with_guessed_format().map_err(IambError::IOError))?;
192
193        let permit = permits
194            .acquire()
195            .await
196            .map_err(|err| IambError::Preview(err.to_string()))?;
197
198        let handle = tokio::task::spawn_blocking(move || {
199            let image = reader.decode().map_err(IambError::Image)?;
200
201            picker
202                .new_protocol(image, size.into(), Resize::Fit(Some(filter)))
203                .map_err(|err| IambError::Preview(err.to_string()))
204        });
205
206        let image = handle.await.map_err(|err| IambError::Preview(err.to_string()))??;
207        std::mem::drop(permit);
208
209        Ok(ImageStatus::Loaded(image))
210    }
211    let key = source.unique_key();
212
213    let filter = store
214        .lock()
215        .await
216        .application
217        .settings
218        .tunables
219        .image_preview
220        .protocol
221        .filter
222        .unwrap_or(FilterType::Triangle);
223
224    let status = match load_image_inner(media, source, picker, permits, size, filter).await {
225        Ok(status) => status,
226        Err(err) => ImageStatus::Error(format!("{err:?}")),
227    };
228
229    let mut locked = store.lock().await;
230    locked.application.previews.insert(key, kind, status);
231}