src/preview.rs
218 lines · 6896 bytes
14 symbols in this file
1use matrix_sdk::Media;
2use matrix_sdk::media::{MediaFormat, MediaRequestParameters, UniqueKey};
3use ratatui_image::picker::Picker;
4use ratatui_image::{FilterType, Resize};
5use tokio::sync::Semaphore;
6
7use crate::config::ImagePreviewValues;
8use crate::prelude::*;
9
10pub enum ImageStatus {
11 Queued(Size),
12 Downloading(Size),
13 Loaded(Arc<SlicedProtocol>),
14 Error(String),
15}
16
17#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
18pub enum PreviewKind {
19 /// A custom `width, height` is given in pixels or defaults to the config
20 Custom(Option<u16>, Option<u16>),
21
22 /// Force the image to be rendered in Emoji presentation (i.e., 1x2 characters)
23 ///
24 /// This is used primarily for custom message reactions and for the `data-mx-emoticon`
25 /// attribute on images, which is typically used when forcing stickers to appear like
26 /// custom Emoji.
27 ///
28 /// In the future, we could potentially investigate using this as a way to also handle
29 /// troublesome ZWJ combinations that confuse terminals or ratatui by not having clear
30 /// widths across implementations.
31 Emoji,
32}
33
34impl Default for PreviewKind {
35 fn default() -> Self {
36 Self::Custom(None, None)
37 }
38}
39
40impl PreviewKind {
41 fn image_size(self, picker: &Picker, image_preview: &ImagePreviewValues) -> Size {
42 match self {
43 Self::Emoji => Size { width: 2, height: 1 },
44 Self::Custom(width, height) => {
45 let font_size = picker.font_size();
46
47 let width = width
48 .map(|width| width.div_ceil(font_size.width))
49 .unwrap_or(image_preview.size.width)
50 .min(image_preview.size.width);
51
52 let height = height
53 .map(|height| height.div_ceil(font_size.height))
54 .unwrap_or(image_preview.size.height)
55 .min(image_preview.size.height);
56
57 Size { width, height }
58 },
59 }
60 }
61}
62
63pub struct PreviewManager {
64 /// Image preview "protocol" picker.
65 picker: Arc<Picker>,
66
67 /// Permits for rendering images in background thread.
68 permits: Arc<Semaphore>,
69
70 /// Indexed by [`MediaSource::unique_key`]
71 previews: HashMap<(String, PreviewKind), ImageStatus>,
72}
73
74impl PreviewManager {
75 pub fn new(settings: &ApplicationSettings) -> Self {
76 let picker = picker_from_settings(settings);
77
78 Self {
79 picker: picker.into(),
80 permits: Arc::new(Semaphore::new(2)),
81 previews: Default::default(),
82 }
83 }
84
85 pub fn get(&self, source: &MediaSource, kind: PreviewKind) -> Option<&ImageStatus> {
86 self.previews.get(&(source.unique_key(), kind))
87 }
88
89 fn insert(&mut self, key: String, kind: PreviewKind, status: ImageStatus) {
90 self.previews.insert((key, kind), status);
91 }
92
93 /// Queue download and preparation of preview
94 pub fn load(&mut self, source: &MediaSource, kind: PreviewKind, worker: &Requester) {
95 let Some(status) = self.previews.get_mut(&(source.unique_key(), kind)) else {
96 return;
97 };
98
99 if let ImageStatus::Queued(size) = status {
100 let size = *size;
101 *status = ImageStatus::Downloading(size);
102
103 worker.load_image(
104 source.to_owned(),
105 kind,
106 size.to_owned(),
107 Arc::clone(&self.picker),
108 Arc::clone(&self.permits),
109 );
110 }
111 }
112
113 pub fn register_preview(
114 &mut self,
115 settings: &ApplicationSettings,
116 source: &MediaSource,
117 kind: PreviewKind,
118 ) {
119 let key = (source.unique_key(), kind);
120 if self.previews.contains_key(&key) {
121 return;
122 }
123
124 let size = kind.image_size(&self.picker, &settings.tunables.image_preview);
125 self.previews.insert(key, ImageStatus::Queued(size));
126 }
127}
128
129fn picker_from_query() -> Picker {
130 // XXX: documentation says to use this query on alternate screen but it seems to be fine
131 Picker::from_query_stdio().unwrap_or_else(|e| {
132 tracing::warn!("Failed to setup image previews (falling back to halfblock rendering): {e}");
133 Picker::halfblocks()
134 })
135}
136
137fn picker_from_settings(settings: &ApplicationSettings) -> Picker {
138 let mut picker = if !settings.tunables.image_preview.enabled {
139 // Skip any auto-detection and use halfblocks when disabled:
140 Picker::halfblocks()
141 } else if let Some(font_size) = settings.tunables.image_preview.protocol.font_size {
142 #[expect(deprecated, reason = "from_query_stdio doesn't work on windows")]
143 Picker::from_fontsize(font_size.into())
144 } else {
145 picker_from_query()
146 };
147
148 // user forced protocol type; use that
149 if let Some(protocol_type) = settings.tunables.image_preview.protocol.r#type {
150 picker.set_protocol_type(protocol_type);
151 }
152
153 picker
154}
155
156pub async fn load_image(
157 store: AsyncProgramStore,
158 media: Media,
159 source: MediaSource,
160 kind: PreviewKind,
161 picker: Arc<Picker>,
162 permits: Arc<Semaphore>,
163 size: Size,
164) {
165 async fn load_image_inner(
166 media: Media,
167 source: MediaSource,
168 picker: Arc<Picker>,
169 permits: Arc<Semaphore>,
170 size: Size,
171 filter: FilterType,
172 ) -> Result<ImageStatus, IambError> {
173 let reader = media
174 .get_media_content(&MediaRequestParameters { source, format: MediaFormat::File }, true)
175 .await
176 .map(std::io::Cursor::new)
177 .map(image::ImageReader::new)
178 .map_err(IambError::Matrix)
179 .and_then(|reader| reader.with_guessed_format().map_err(IambError::IOError))?;
180
181 let permit = permits
182 .acquire()
183 .await
184 .map_err(|err| IambError::Preview(err.to_string()))?;
185
186 let handle = tokio::task::spawn_blocking(move || {
187 let image = reader.decode().map_err(IambError::Image)?;
188
189 SlicedProtocol::new_with_resize(&picker, image, size, Resize::Fit(Some(filter)))
190 .map_err(|err| IambError::Preview(err.to_string()))
191 });
192
193 let image = handle.await.map_err(|err| IambError::Preview(err.to_string()))??;
194 std::mem::drop(permit);
195
196 Ok(ImageStatus::Loaded(Arc::new(image)))
197 }
198 let key = source.unique_key();
199
200 let filter = store
201 .lock()
202 .await
203 .application
204 .settings
205 .tunables
206 .image_preview
207 .protocol
208 .filter
209 .unwrap_or(FilterType::Triangle);
210
211 let status = match load_image_inner(media, source, picker, permits, size, filter).await {
212 Ok(status) => status,
213 Err(err) => ImageStatus::Error(format!("{err:?}")),
214 };
215
216 let mut locked = store.lock().await;
217 locked.application.previews.insert(key, kind, status);
218}