Commit 5cf88f6107

5cf88f61077ede664a97fc338119658683807766

parent: c0980df71a

Unregistered key

vaw <git@nlih.de> · 2026-08-31 23:57 UTC
committer: <noreply@github.com>

Image Preview improvements (#653)

Layout: unified · split

Cargo.lock +4 −2
@@ -2582,6 +2582,7 @@ dependencies = [
2582 "ravif", 2582 "ravif",
2583 "rayon", 2583 "rayon",
2584 "rgb", 2584 "rgb",
2585 "serde",
2585 "tiff", 2586 "tiff",
2586 "zune-core", 2587 "zune-core",
2587 "zune-jpeg", 2588 "zune-jpeg",
@@ -4472,13 +4473,14 @@ dependencies = [
4472 4473
4473[[package]] 4474[[package]]
4474name = "ratatui-image" 4475name = "ratatui-image"
4475version = "8.1.1" 4476version = "9.0.0"
4476source = "registry+https://github.com/rust-lang/crates.io-index" 4477source = "registry+https://github.com/rust-lang/crates.io-index"
4477checksum = "3ecc67e9f7d0ac69e0f712f58b1a9d5a04d8daeeb3628f4d6b67580abb88b7cb" 4478checksum = "5dbebe428e366c230b2251c7091f2a56ec2bf818d96cdc807f6474428ee09040"
4478dependencies = [ 4479dependencies = [
4479 "base64-simd", 4480 "base64-simd",
4480 "icy_sixel", 4481 "icy_sixel",
4481 "image", 4482 "image",
4483 "pkg-config",
4482 "rand 0.8.6", 4484 "rand 0.8.6",
4483 "ratatui", 4485 "ratatui",
4484 "rustix 0.38.44", 4486 "rustix 0.38.44",
Cargo.toml +8 −2
@@ -21,6 +21,8 @@ desktop = ["dep:notify-rust", "modalkit/clipboard"]
21max_level_warn = ["tracing/max_level_warn"] 21max_level_warn = ["tracing/max_level_warn"]
22max_level_error = ["tracing/max_level_error"] 22max_level_error = ["tracing/max_level_error"]
23max_level_off = ["tracing/max_level_off"] 23max_level_off = ["tracing/max_level_off"]
24chafa-dyn = ["ratatui-image/chafa-dyn"]
25chafa-static = ["ratatui-image/chafa-static"]
24 26
25[build-dependencies.vergen-gitcl] 27[build-dependencies.vergen-gitcl]
26version = "9" 28version = "9"
@@ -43,7 +45,7 @@ gethostname = "1.1"
43html5ever = "0.39.0" 45html5ever = "0.39.0"
44http-serde = "2.1.1" 46http-serde = "2.1.1"
45humansize = "2.0.0" 47humansize = "2.0.0"
46image = "0.25.6" 48image = {version = "0.25.6", features = ["serde"], default-features = false}
47libc = "0.2" 49libc = "0.2"
48linkify = "0.11.0" 50linkify = "0.11.0"
49markup5ever_rcdom = "0.39" 51markup5ever_rcdom = "0.39"
@@ -53,7 +55,6 @@ nom = "8.0"
53open = "5.0.0" 55open = "5.0.0"
54rand = "0.10" 56rand = "0.10"
55ratatui = "0.29.0" 57ratatui = "0.29.0"
56ratatui-image = { version = "8.0", features = ["serde"] }
57regex = "1.5" 58regex = "1.5"
58rpassword = "7.2" 59rpassword = "7.2"
59serde = "1.0" 60serde = "1.0"
@@ -105,6 +106,11 @@ version = "0.18.0"
105version = "1.24.1" 106version = "1.24.1"
106features = ["macros", "net", "rt-multi-thread", "sync", "time"] 107features = ["macros", "net", "rt-multi-thread", "sync", "time"]
107 108
109[dependencies.ratatui-image]
110version = "9.0"
111default-features = false
112features = ["serde", "crossterm", "image-defaults"]
113
108[dev-dependencies] 114[dev-dependencies]
109lazy_static = "1.4.0" 115lazy_static = "1.4.0"
110pretty_assertions = "1.4.0" 116pretty_assertions = "1.4.0"
README.md +12 −3
@@ -79,9 +79,18 @@ cargo install --profile release-light --features max_level_error --path .
79``` 79```
80 80
81Add `--no-default-features` if you want to skip desktop integration (e.g. 81Add `--no-default-features` if you want to skip desktop integration (e.g.
82clipboard and notifications support) and you would like to link against 82clipboard and notifications support) and you would like to link against your
83your system's OpenSSL and SQLite instead of using rustls and a bundled 83system's SQLite instead of using a bundled SQLite.
84SQLite. 84
85### Crate features
86
87- `bundled`: use bundled SQLite instead of system library (default)
88- `desktop`: enable desktop notifications and clipboard support (default)
89- `max_level_warn`: disable support for more verbose logging than the default `warn` level
90- `max_level_error`: disable support for more verbose logging than the `error` level
91- `max_level_off`: disable all logs at compile time
92- `chafa-dyn`: use [chafa](https://hpjansson.org/chafa/) as a dynamic library for halfblock rendering
93- `chafa-static`: use [chafa](https://hpjansson.org/chafa/) as a static library for halfblock rendering
85 94
86## Installation (via `crates.io`) 95## Installation (via `crates.io`)
87 96
config.example.toml +1 −1
@@ -29,7 +29,7 @@ indicator = "only-encrypted"
29indicator_location = "title|prompt" 29indicator_location = "title|prompt"
30 30
31[settings.image_preview] 31[settings.image_preview]
32protocol.type = "sixel" 32protocol = { type = "sixel", filter = "Nearest" }
33size = { "width" = 66, "height" = 10 } 33size = { "width" = 66, "height" = 10 }
34 34
35[settings.proxy] 35[settings.proxy]
docs/iamb.5 +55 −32
@@ -161,37 +161,9 @@ for more details.
161.It Sy external_edit_file_suffix 161.It Sy external_edit_file_suffix
162Suffix to append to temporary file names when using the :editor command. Defaults to .md. 162Suffix to append to temporary file names when using the :editor command. Defaults to .md.
163.It Sy image_preview 163.It Sy image_preview
164Enable image previews and configure it. 164Subsection for configuring image previews. See
165An empty object will enable the feature with default settings, omitting it will disable the feature. 165.Sx "IMAGE PREVIEWS"
166The available fields in this object are: 166for more details.
167.Bl -tag -width Ds
168.It Sy lazy_load
169If
170.Sy true
171(the default), download and render image previews when viewing a message with an image.
172If
173.Sy false ,
174load previews as soon as a message with an image is received.
175.It Sy size
176An optional object with
177.Sy width
178and
179.Sy height
180fields to specify the preview size in cells.
181Defaults to 66 and 10.
182.It Sy protocol
183An optional object to override settings that will normally be guessed automatically:
184.Bl -tag -width Ds
185.It Sy type
186An optional string set to one of the protocol types:
187.Dq Sy sixel ,
188.Dq Sy kitty ,
189and
190.Dq Sy halfblocks .
191.It Sy font_size
192An optional list of two numbers representing font width and height in pixels.
193.El
194.El
195.It Sy log_level 167.It Sy log_level
196Specifies the lowest log level that should be shown. 168Specifies the lowest log level that should be shown.
197Possible values are: 169Possible values are:
@@ -240,7 +212,7 @@ for more details.
240Defines a custom command and its arguments to run when opening downloads instead of the default. 212Defines a custom command and its arguments to run when opening downloads instead of the default.
241(For example, 213(For example,
242.Sy ["my-open",\ "--file"] . ) 214.Sy ["my-open",\ "--file"] . )
243.Sy proxy 215.It Sy proxy
244When this subsection is present, you can configure how requests are proxied to the homeserver. 216When this subsection is present, you can configure how requests are proxied to the homeserver.
245See 217See
246.Sx PROXYING 218.Sx PROXYING
@@ -353,6 +325,57 @@ and
353Both can be used via 325Both can be used via
354.Dq Sy title|prompt . 326.Dq Sy title|prompt .
355.El 327.El
328.Sh IMAGE PREVIEWS
329The
330.Sy settings.image_preview
331subsection allows configuring image previews.
332.Pp
333The available fields in this subsection are:
334.Bl -tag -width Ds
335.It Sy enabled
336Defaults to
337.Sy true .
338.It Sy lazy_load
339If
340.Sy true
341(the default), download and render image previews when viewing a message with an image.
342If
343.Sy false ,
344load previews as soon as a message with an image is received.
345.It Sy size
346An optional object with
347.Sy width
348and
349.Sy height
350fields to specify the preview size in cells.
351Defaults to 66 and 10.
352.It Sy protocol
353An optional object to override settings that will normally be guessed automatically:
354.Bl -tag -width Ds
355.It Sy type
356An optional string set to one of the protocol types:
357.Dq Sy sixel ,
358.Dq Sy kitty ,
359.Dq Sy iterm2 ,
360and
361.Dq Sy halfblocks .
362.It Sy font_size
363An optional list of two numbers representing font width and height in pixels.
364.It Sy filter
365The sample filter used to scale images.
366Possible values are:
367.Dq Sy Nearest ,
368.Dq Sy Triangle
369(default) ,
370.Dq Sy CatmullRom ,
371.Dq Sy Gaussian ,
372and
373.Dq Sy Lanczos3 .
374See
375.Lk https://docs.rs/image/0.25.10/image/imageops/enum.FilterType.html
376for more information.
377.El
378.El
356.Sh MOUSE 379.Sh MOUSE
357The 380The
358.Sy settings.mouse 381.Sy settings.mouse
src/base.rs +14 −72
@@ -19,7 +19,6 @@ use ratatui::{
19 text::{Line, Span}, 19 text::{Line, Span},
20 widgets::{Paragraph, Widget}, 20 widgets::{Paragraph, Widget},
21}; 21};
22use ratatui_image::picker::{Picker, ProtocolType};
23use serde::{ 22use serde::{
24 Deserialize, 23 Deserialize,
25 Deserializer, 24 Deserializer,
@@ -98,10 +97,9 @@ use modalkit::{
98 prelude::{CommandType, MoveDir1D, WordStyle}, 97 prelude::{CommandType, MoveDir1D, WordStyle},
99}; 98};
100 99
101use crate::config::ImagePreviewSize;
102use crate::preview::PreviewKind; 100use crate::preview::PreviewKind;
103use crate::{ 101use crate::{
104 config::{ApplicationSettings, ImagePreviewProtocolValues}, 102 config::ApplicationSettings,
105 message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages}, 103 message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages},
106 notifications::NotificationHandle, 104 notifications::NotificationHandle,
107 preview::PreviewManager, 105 preview::PreviewManager,
@@ -1340,16 +1338,10 @@ impl RoomInfo {
1340 content: StickerEventContent { source, .. }, 1338 content: StickerEventContent { source, .. },
1341 .. 1339 ..
1342 }) = &sticker && 1340 }) = &sticker &&
1343 let Some(image_preview) = &settings.tunables.image_preview 1341 settings.tunables.image_preview.enabled
1344 { 1342 {
1345 let source = source.clone().into(); 1343 let source = source.clone().into();
1346 previews.register_preview( 1344 previews.register_preview(settings, &source, PreviewKind::Message, worker);
1347 settings,
1348 &source,
1349 PreviewKind::Message,
1350 image_preview.size,
1351 worker,
1352 );
1353 } 1345 }
1354 1346
1355 let loc = EventLocation::Message(thread_root.clone(), key.clone()); 1347 let loc = EventLocation::Message(thread_root.clone(), key.clone());
@@ -1371,18 +1363,19 @@ impl RoomInfo {
1371 return; 1363 return;
1372 }; 1364 };
1373 let image_uri = OwnedMxcUri::from(orig_react.content.relates_to.key.as_str()); 1365 let image_uri = OwnedMxcUri::from(orig_react.content.relates_to.key.as_str());
1374 let source = if image_uri.is_valid() && settings.tunables.image_preview.is_some() { 1366 let source = if image_uri.is_valid() && settings.tunables.image_preview.enabled {
1375 Some(MediaSource::Plain(image_uri)) 1367 Some(MediaSource::Plain(image_uri))
1376 } else { 1368 } else {
1377 None 1369 None
1378 }; 1370 };
1379 1371
1380 self.insert_reaction(react, source.clone()); 1372 if settings.tunables.image_preview.enabled &&
1381 1373 let Some(source) = source.as_ref()
1382 if let (Some(source), Some(_)) = (source, &settings.tunables.image_preview) { 1374 {
1383 let size = ImagePreviewSize { width: 2, height: 1 }; 1375 previews.register_preview(settings, source, PreviewKind::Reaction, worker);
1384 previews.register_preview(settings, &source, PreviewKind::Reaction, size, worker);
1385 } 1376 }
1377
1378 self.insert_reaction(react, source);
1386 } 1379 }
1387 1380
1388 /// Insert an edit. 1381 /// Insert an edit.
@@ -1530,15 +1523,9 @@ impl RoomInfo {
1530 content: RoomMessageEventContent { msgtype: MessageType::Image(c), .. }, 1523 content: RoomMessageEventContent { msgtype: MessageType::Image(c), .. },
1531 .. 1524 ..
1532 }) = &ev && 1525 }) = &ev &&
1533 let Some(image_preview) = &settings.tunables.image_preview 1526 settings.tunables.image_preview.enabled
1534 { 1527 {
1535 previews.register_preview( 1528 previews.register_preview(settings, &c.source, PreviewKind::Message, worker)
1536 settings,
1537 &c.source,
1538 PreviewKind::Message,
1539 image_preview.size,
1540 worker,
1541 )
1542 } 1529 }
1543 1530
1544 self.insert(ev); 1531 self.insert(ev);
@@ -1733,51 +1720,6 @@ fn emoji_map() -> CompletionMap<String, &'static Emoji> {
1733 return emojis; 1720 return emojis;
1734} 1721}
1735 1722
1736#[cfg(unix)]
1737fn picker_from_termios(protocol_type: Option<ProtocolType>) -> Option<Picker> {
1738 let mut picker = match Picker::from_query_stdio() {
1739 Ok(picker) => picker,
1740 Err(e) => {
1741 tracing::error!("Failed to setup image previews: {e}");
1742 return None;
1743 },
1744 };
1745
1746 if let Some(protocol_type) = protocol_type {
1747 picker.set_protocol_type(protocol_type);
1748 }
1749
1750 Some(picker)
1751}
1752
1753/// Windows cannot guess the right protocol, and always needs type and font_size.
1754#[cfg(windows)]
1755fn picker_from_termios(_: Option<ProtocolType>) -> Option<Picker> {
1756 tracing::error!(
1757 "\"image_preview\" requires \"protocol\" with \"type\" and \"font_size\" options on Windows."
1758 );
1759 None
1760}
1761
1762fn picker_from_settings(settings: &ApplicationSettings) -> Option<Picker> {
1763 let image_preview = settings.tunables.image_preview.as_ref()?;
1764 let image_preview_protocol = image_preview.protocol.as_ref();
1765
1766 if let Some(&ImagePreviewProtocolValues {
1767 r#type: Some(protocol_type),
1768 font_size: Some(font_size),
1769 }) = image_preview_protocol
1770 {
1771 // User forced type and font_size: use that.
1772 let mut picker = Picker::from_fontsize(font_size);
1773 picker.set_protocol_type(protocol_type);
1774 Some(picker)
1775 } else {
1776 // Guess, but use type if forced.
1777 picker_from_termios(image_preview_protocol.and_then(|p| p.r#type))
1778 }
1779}
1780
1781/// Information gathered during server syncs about joined rooms. 1723/// Information gathered during server syncs about joined rooms.
1782#[derive(Default)] 1724#[derive(Default)]
1783pub struct SyncInfo { 1725pub struct SyncInfo {
@@ -1922,12 +1864,12 @@ pub struct ChatStore {
1922impl ChatStore { 1864impl ChatStore {
1923 /// Create a new [ChatStore]. 1865 /// Create a new [ChatStore].
1924 pub fn new(worker: Requester, settings: ApplicationSettings) -> Self { 1866 pub fn new(worker: Requester, settings: ApplicationSettings) -> Self {
1925 let picker = picker_from_settings(&settings); 1867 let previews = PreviewManager::new(&settings);
1926 1868
1927 ChatStore { 1869 ChatStore {
1928 worker, 1870 worker,
1929 settings, 1871 settings,
1930 previews: PreviewManager::new(picker), 1872 previews,
1931 cmds: crate::commands::setup_commands(), 1873 cmds: crate::commands::setup_commands(),
1932 emojis: emoji_map(), 1874 emojis: emoji_map(),
1933 1875
src/config.rs +11 −6
@@ -19,6 +19,7 @@ use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue};
19use matrix_sdk::ruma::{OwnedDeviceId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId}; 19use matrix_sdk::ruma::{OwnedDeviceId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId};
20use ratatui::style::{Color, Modifier as StyleModifier, Style}; 20use ratatui::style::{Color, Modifier as StyleModifier, Style};
21use ratatui::text::Span; 21use ratatui::text::Span;
22use ratatui_image::FilterType;
22use ratatui_image::picker::ProtocolType; 23use ratatui_image::picker::ProtocolType;
23use serde::{Deserialize, Deserializer, Serialize, de::Error as SerdeError, de::Visitor}; 24use serde::{Deserialize, Deserializer, Serialize, de::Error as SerdeError, de::Visitor};
24use url::Url; 25use url::Url;
@@ -692,24 +693,27 @@ pub struct Notifications {
692 693
693#[derive(Clone)] 694#[derive(Clone)]
694pub struct ImagePreviewValues { 695pub struct ImagePreviewValues {
696 pub enabled: bool,
695 pub lazy_load: bool, 697 pub lazy_load: bool,
696 pub size: ImagePreviewSize, 698 pub size: ImagePreviewSize,
697 pub protocol: Option<ImagePreviewProtocolValues>, 699 pub protocol: ImagePreviewProtocolValues,
698} 700}
699 701
700#[derive(Clone, Debug, Default, Deserialize)] 702#[derive(Clone, Debug, Default, Deserialize)]
701pub struct ImagePreview { 703pub struct ImagePreview {
704 pub enabled: Option<bool>,
702 pub lazy_load: Option<bool>, 705 pub lazy_load: Option<bool>,
703 pub size: Option<ImagePreviewSize>, 706 pub size: Option<ImagePreviewSize>,
704 pub protocol: Option<ImagePreviewProtocolValues>, 707 pub protocol: Option<ImagePreviewProtocolValues>,
705} 708}
706 709
707impl ImagePreview { 710impl ImagePreview {
708 fn values(self) -> ImagePreviewValues { 711 pub fn values(self) -> ImagePreviewValues {
709 ImagePreviewValues { 712 ImagePreviewValues {
713 enabled: self.enabled.unwrap_or(true),
710 lazy_load: self.lazy_load.unwrap_or(true), 714 lazy_load: self.lazy_load.unwrap_or(true),
711 size: self.size.unwrap_or_default(), 715 size: self.size.unwrap_or_default(),
712 protocol: self.protocol, 716 protocol: self.protocol.unwrap_or_default(),
713 } 717 }
714 } 718 }
715} 719}
@@ -726,9 +730,10 @@ impl Default for ImagePreviewSize {
726 } 730 }
727} 731}
728 732
729#[derive(Clone, Debug, Deserialize)] 733#[derive(Clone, Debug, Deserialize, Default)]
730pub struct ImagePreviewProtocolValues { 734pub struct ImagePreviewProtocolValues {
731 pub r#type: Option<ProtocolType>, 735 pub r#type: Option<ProtocolType>,
736 pub filter: Option<FilterType>,
732 pub font_size: Option<(u16, u16)>, 737 pub font_size: Option<(u16, u16)>,
733} 738}
734 739
@@ -833,7 +838,7 @@ pub struct TunableValues {
833 pub mouse: Mouse, 838 pub mouse: Mouse,
834 pub notifications: Notifications, 839 pub notifications: Notifications,
835 pub terminal: TerminalValues, 840 pub terminal: TerminalValues,
836 pub image_preview: Option<ImagePreviewValues>, 841 pub image_preview: ImagePreviewValues,
837 pub user_gutter_width: usize, 842 pub user_gutter_width: usize,
838 pub external_edit_file_suffix: String, 843 pub external_edit_file_suffix: String,
839 pub tabstop: usize, 844 pub tabstop: usize,
@@ -971,7 +976,7 @@ impl Tunables {
971 open_command: self.open_command, 976 open_command: self.open_command,
972 mouse: self.mouse.unwrap_or_default(), 977 mouse: self.mouse.unwrap_or_default(),
973 notifications: self.notifications.unwrap_or_default(), 978 notifications: self.notifications.unwrap_or_default(),
974 image_preview: self.image_preview.map(ImagePreview::values), 979 image_preview: self.image_preview.unwrap_or_default().values(),
975 user_gutter_width: self.user_gutter_width.unwrap_or(30), 980 user_gutter_width: self.user_gutter_width.unwrap_or(30),
976 external_edit_file_suffix: self 981 external_edit_file_suffix: self
977 .external_edit_file_suffix 982 .external_edit_file_suffix
src/message/printer.rs +1 −1
@@ -52,7 +52,7 @@ impl<'a> TextPrinter<'a> {
52 52
53 /// The `(x, y)` position where the next text will be printed. 53 /// The `(x, y)` position where the next text will be printed.
54 pub fn cursor_pos(&self) -> (usize, usize) { 54 pub fn cursor_pos(&self) -> (usize, usize) {
55 (self.curr_width, self.text.lines.len().saturating_sub(1)) 55 (self.curr_width, self.text.lines.len())
56 } 56 }
57 57
58 /// Configure the alignment for each line. 58 /// Configure the alignment for each line.
src/preview.rs +69 −22
@@ -6,12 +6,12 @@ use matrix_sdk::{
6 ruma::events::room::MediaSource, 6 ruma::events::room::MediaSource,
7}; 7};
8use ratatui::layout::Rect; 8use ratatui::layout::Rect;
9use ratatui_image::{Resize, picker::Picker, protocol::Protocol}; 9use ratatui_image::{FilterType, Resize, picker::Picker, protocol::Protocol};
10use tokio::sync::Semaphore; 10use tokio::sync::Semaphore;
11 11
12use crate::{ 12use crate::{
13 base::{AsyncProgramStore, IambError}, 13 base::{AsyncProgramStore, IambError},
14 config::{ApplicationSettings, ImagePreviewSize}, 14 config::{ApplicationSettings, ImagePreviewSize, ImagePreviewValues},
15 worker::Requester, 15 worker::Requester,
16}; 16};
17 17
@@ -28,9 +28,18 @@ pub enum PreviewKind {
28 Reaction, 28 Reaction,
29} 29}
30 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
31pub struct PreviewManager { 40pub struct PreviewManager {
32 /// Image preview "protocol" picker. 41 /// Image preview "protocol" picker.
33 picker: Option<Arc<Picker>>, 42 picker: Arc<Picker>,
34 43
35 /// Permits for rendering images in background thread. 44 /// Permits for rendering images in background thread.
36 permits: Arc<Semaphore>, 45 permits: Arc<Semaphore>,
@@ -40,9 +49,11 @@ pub struct PreviewManager {
40} 49}
41 50
42impl PreviewManager { 51impl PreviewManager {
43 pub fn new(picker: Option<Picker>) -> Self { 52 pub fn new(settings: &ApplicationSettings) -> Self {
53 let picker = picker_from_settings(settings);
54
44 Self { 55 Self {
45 picker: picker.map(Into::into), 56 picker: picker.into(),
46 permits: Arc::new(Semaphore::new(2)), 57 permits: Arc::new(Semaphore::new(2)),
47 previews: Default::default(), 58 previews: Default::default(),
48 } 59 }
@@ -61,7 +72,6 @@ impl PreviewManager {
61 let Some(status) = self.previews.get_mut(&(source.unique_key(), kind)) else { 72 let Some(status) = self.previews.get_mut(&(source.unique_key(), kind)) else {
62 return; 73 return;
63 }; 74 };
64 let Some(picker) = &self.picker else { return };
65 75
66 if let ImageStatus::Queued(size) = status { 76 if let ImageStatus::Queued(size) = status {
67 let size = *size; 77 let size = *size;
@@ -71,7 +81,7 @@ impl PreviewManager {
71 source.to_owned(), 81 source.to_owned(),
72 kind, 82 kind,
73 size.to_owned(), 83 size.to_owned(),
74 Arc::clone(picker), 84 Arc::clone(&self.picker),
75 Arc::clone(&self.permits), 85 Arc::clone(&self.permits),
76 ); 86 );
77 } 87 }
@@ -82,30 +92,55 @@ impl PreviewManager {
82 settings: &ApplicationSettings, 92 settings: &ApplicationSettings,
83 source: &MediaSource, 93 source: &MediaSource,
84 kind: PreviewKind, 94 kind: PreviewKind,
85 size: ImagePreviewSize,
86 worker: &Requester, 95 worker: &Requester,
87 ) { 96 ) {
88 if self.picker.is_none() {
89 return;
90 }
91
92 let key = (source.unique_key(), kind); 97 let key = (source.unique_key(), kind);
93 if self.previews.contains_key(&key) { 98 if self.previews.contains_key(&key) {
94 return; 99 return;
95 } 100 }
101
102 let size = kind.image_size(&settings.tunables.image_preview);
96 self.previews.insert(key, ImageStatus::Queued(size)); 103 self.previews.insert(key, ImageStatus::Queued(size));
97 104
98 if settings 105 if settings.tunables.image_preview.enabled && !settings.tunables.image_preview.lazy_load {
99 .tunables
100 .image_preview
101 .as_ref()
102 .is_some_and(|setting| !setting.lazy_load)
103 {
104 self.load(source, kind, worker); 106 self.load(source, kind, worker);
105 } 107 }
106 } 108 }
107} 109}
108 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)
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
109impl From<ImagePreviewSize> for Rect { 144impl From<ImagePreviewSize> for Rect {
110 fn from(value: ImagePreviewSize) -> Self { 145 fn from(value: ImagePreviewSize) -> Self {
111 Rect::new(0, 0, value.width as _, value.height as _) 146 Rect::new(0, 0, value.width as _, value.height as _)
@@ -132,6 +167,7 @@ pub async fn load_image(
132 picker: Arc<Picker>, 167 picker: Arc<Picker>,
133 permits: Arc<Semaphore>, 168 permits: Arc<Semaphore>,
134 size: ImagePreviewSize, 169 size: ImagePreviewSize,
170 filter: FilterType,
135 ) -> Result<ImageStatus, IambError> { 171 ) -> Result<ImageStatus, IambError> {
136 let reader = media 172 let reader = media
137 .get_media_content(&MediaRequestParameters { source, format: MediaFormat::File }, true) 173 .get_media_content(&MediaRequestParameters { source, format: MediaFormat::File }, true)
@@ -141,16 +177,16 @@ pub async fn load_image(
141 .map_err(IambError::Matrix) 177 .map_err(IambError::Matrix)
142 .and_then(|reader| reader.with_guessed_format().map_err(IambError::IOError))?; 178 .and_then(|reader| reader.with_guessed_format().map_err(IambError::IOError))?;
143 179
144 let image = reader.decode().map_err(IambError::Image)?;
145
146 let permit = permits 180 let permit = permits
147 .acquire() 181 .acquire()
148 .await 182 .await
149 .map_err(|err| IambError::Preview(err.to_string()))?; 183 .map_err(|err| IambError::Preview(err.to_string()))?;
150 184
151 let handle = tokio::task::spawn_blocking(move || { 185 let handle = tokio::task::spawn_blocking(move || {
186 let image = reader.decode().map_err(IambError::Image)?;
187
152 picker 188 picker
153 .new_protocol(image, size.into(), Resize::Fit(None)) 189 .new_protocol(image, size.into(), Resize::Fit(Some(filter)))
154 .map_err(|err| IambError::Preview(err.to_string())) 190 .map_err(|err| IambError::Preview(err.to_string()))
155 }); 191 });
156 192
@@ -161,7 +197,18 @@ pub async fn load_image(
161 } 197 }
162 let key = source.unique_key(); 198 let key = source.unique_key();
163 199
164 let status = match load_image_inner(media, source, picker, permits, size).await { 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 {
165 Ok(status) => status, 212 Ok(status) => status,
166 Err(err) => ImageStatus::Error(format!("{err:?}")), 213 Err(err) => ImageStatus::Error(format!("{err:?}")),
167 }; 214 };
src/tests.rs +2 −2
@@ -1,7 +1,6 @@
1use std::path::PathBuf; 1use std::path::PathBuf;
2use std::{collections::HashMap, iter::FromIterator as _}; 2use std::{collections::HashMap, iter::FromIterator as _};
3 3
4use matrix_sdk::ruma::MilliSecondsSinceUnixEpoch;
5use matrix_sdk::ruma::{ 4use matrix_sdk::ruma::{
6 EventId, 5 EventId,
7 OwnedEventId, 6 OwnedEventId,
@@ -14,6 +13,7 @@ use matrix_sdk::ruma::{
14 server_name, 13 server_name,
15 user_id, 14 user_id,
16}; 15};
16use matrix_sdk::ruma::{MilliSecondsSinceUnixEpoch, assign};
17 17
18use lazy_static::lazy_static; 18use lazy_static::lazy_static;
19use ratatui::style::{Color, Style}; 19use ratatui::style::{Color, Style};
@@ -202,7 +202,7 @@ pub fn mock_tunables() -> TunableValues {
202 show_message: true, 202 show_message: true,
203 sound_hint: None, 203 sound_hint: None,
204 }, 204 },
205 image_preview: None, 205 image_preview: assign!(ImagePreview::default().values(), {enabled: false}),
206 user_gutter_width: 30, 206 user_gutter_width: 30,
207 tabstop: 4, 207 tabstop: 4,
208 members_split: Default::default(), 208 members_split: Default::default(),
src/windows/room/scrollback.rs +25 −23
@@ -1364,34 +1364,36 @@ impl StatefulWidget for Scrollback<'_> {
1364 let mut prev = prevmsg(&corner_key, thread); 1364 let mut prev = prevmsg(&corner_key, thread);
1365 1365
1366 // load image previews 1366 // load image previews
1367 for (key, item) in thread.range(&corner_key..).rev() { 1367 if settings.tunables.image_preview.enabled {
1368 if let Some(source) = item.image_preview() { 1368 for (key, item) in thread.range(&corner_key..).rev() {
1369 self.store.application.previews.load( 1369 if let Some(source) = item.image_preview() {
1370 source,
1371 PreviewKind::Message,
1372 &self.store.application.worker,
1373 );
1374 }
1375 let reply = item
1376 .reply_to()
1377 .or_else(|| item.thread_root())
1378 .and_then(|e| info.get_event(&e))
1379 .and_then(|msg| msg.image_preview());
1380 if let Some(source) = reply {
1381 self.store.application.previews.load(
1382 source,
1383 PreviewKind::Message,
1384 &self.store.application.worker,
1385 );
1386 }
1387 if let Some(event_id) = key.id.as_origin() {
1388 for source in info.get_reaction_images(event_id) {
1389 self.store.application.previews.load( 1370 self.store.application.previews.load(
1390 source, 1371 source,
1391 PreviewKind::Reaction, 1372 PreviewKind::Message,
1392 &self.store.application.worker, 1373 &self.store.application.worker,
1393 ); 1374 );
1394 } 1375 }
1376 let reply = item
1377 .reply_to()
1378 .or_else(|| item.thread_root())
1379 .and_then(|e| info.get_event(&e))
1380 .and_then(|msg| msg.image_preview());
1381 if let Some(source) = reply {
1382 self.store.application.previews.load(
1383 source,
1384 PreviewKind::Message,
1385 &self.store.application.worker,
1386 );
1387 }
1388 if let Some(event_id) = key.id.as_origin() {
1389 for source in info.get_reaction_images(event_id) {
1390 self.store.application.previews.load(
1391 source,
1392 PreviewKind::Reaction,
1393 &self.store.application.worker,
1394 );
1395 }
1396 }
1395 } 1397 }
1396 } 1398 }
1397 1399