Commit 78b8573f26

78b8573f26f67c376c6087301528cded4ee56825

parent: 4593c3f5a1

Unregistered key

vaw <vaw@nlih.de> · 2026-08-21 22:07 UTC
committer: <noreply@github.com>

MSC4027: Display image reactions (#518)

Layout: unified · split

docs/iamb.5 +6
@@ -126,6 +126,12 @@ These options are configured as an object under the
126126key and can be overridden as described in
127127.Sx PROFILES .
128128.Bl -tag -width Ds
129.It Sy cache_policy
130Configure how downloaded files and image previews are cached internally.
131Specifying this object will replace the upstream defaults and possibly lead to unconstrained cache growth.
132Possible keys and their effect are documented at:
133.br
134.Lk https://docs.rs/matrix-sdk/latest/matrix_sdk/media/struct.MediaRetentionPolicy.html#fields
129135.It Sy default_markup
130136Controls how text in the message bar is interpreted by default.
131137Possible values are
src/base.rs +83 −33
@@ -13,6 +13,7 @@ use std::time::{Duration, Instant};
1313
1414use emojis::Emoji;
1515
16use matrix_sdk::ruma::OwnedMxcUri;
1617use matrix_sdk::ruma::OwnedTransactionId;
1718use matrix_sdk::ruma::events::receipt::ReceiptThread;
1819use matrix_sdk::ruma::events::room::MediaSource;
@@ -93,6 +94,8 @@ use modalkit::{
9394 prelude::{CommandType, WordStyle},
9495};
9596
97use crate::config::ImagePreviewSize;
98use crate::preview::PreviewKind;
9699use crate::{
97100 config::{ApplicationSettings, ImagePreviewProtocolValues},
98101 message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages},
@@ -702,7 +705,7 @@ pub type IambResult<T> = UIResult<T, IambInfo>;
702705///
703706/// The event identifier used as a key here is the ID for the reaction, and not for the message
704707/// it's reacting to.
705pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId)>;
708pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId, Option<MediaSource>)>;
706709
707710pub type MessageEdits = BTreeMap<MessageKey, RoomMessageEventContentWithoutRelation>;
708711
@@ -1133,22 +1136,25 @@ impl RoomInfo {
11331136 }
11341137
11351138 /// Get the reactions and their counts for a message.
1136 pub fn get_reactions(&self, event_id: &EventId) -> Vec<(&str, usize)> {
1139 pub fn get_reactions(&self, event_id: &EventId) -> Vec<(&str, usize, &Option<MediaSource>)> {
11371140 if let Some(reacts) = self.reactions.get(event_id) {
11381141 let mut counts = HashMap::new();
11391142
11401143 let mut seen_user_reactions = BTreeSet::new();
11411144
1142 for (key, user) in reacts.values() {
1145 for (key, user, source) in reacts.values() {
11431146 if !seen_user_reactions.contains(&(key, user)) {
11441147 seen_user_reactions.insert((key, user));
1145 let count = counts.entry(key.as_str()).or_default();
1146 *count += 1;
1148 let count = counts.entry(key.as_str()).or_insert((0, source));
1149 count.0 += 1;
11471150 }
11481151 }
11491152
1150 let mut reactions = counts.into_iter().collect::<Vec<_>>();
1151 reactions.sort();
1153 let mut reactions = counts
1154 .into_iter()
1155 .map(|(key, (count, source))| (key, count, source))
1156 .collect::<Vec<_>>();
1157 reactions.sort_by_key(|item| (item.0, item.1));
11521158
11531159 reactions
11541160 } else {
@@ -1156,6 +1162,14 @@ impl RoomInfo {
11561162 }
11571163 }
11581164
1165 pub fn get_reaction_images(&self, event_id: &EventId) -> impl Iterator<Item = &MediaSource> {
1166 self.reactions
1167 .get(event_id)
1168 .map(HashMap::iter)
1169 .unwrap_or_default()
1170 .filter_map(|(_, (_, _, source))| source.as_ref())
1171 }
1172
11591173 /// Map an event identifier to its [MessageKey].
11601174 pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> {
11611175 self.keys.get(event_id)?.to_message_key()
@@ -1233,25 +1247,21 @@ impl RoomInfo {
12331247 }
12341248
12351249 /// Insert a reaction to a message.
1236 pub fn insert_reaction(&mut self, react: ReactionEvent) {
1237 match react {
1238 MessageLikeEvent::Original(react) => {
1239 let rel_id = react.content.relates_to.event_id;
1240 let key = react.content.relates_to.key;
1250 fn insert_reaction(&mut self, react: ReactionEvent, source: Option<MediaSource>) {
1251 let MessageLikeEvent::Original(react) = react else {
1252 return;
1253 };
1254 let rel_id = react.content.relates_to.event_id;
1255 let key = react.content.relates_to.key;
12411256
1242 let message = self.reactions.entry(rel_id.clone()).or_default();
1243 let event_id = react.event_id;
1244 let user_id = react.sender;
1257 let message = self.reactions.entry(rel_id.clone()).or_default();
1258 let event_id = react.event_id;
1259 let user_id = react.sender;
12451260
1246 message.insert(event_id.clone(), (key, user_id));
1261 message.insert(event_id.clone(), (key, user_id, source));
12471262
1248 let loc = EventLocation::Reaction(rel_id);
1249 self.keys.insert(event_id, loc);
1250 },
1251 MessageLikeEvent::Redacted(_) => {
1252 return;
1253 },
1254 }
1263 let loc = EventLocation::Reaction(rel_id);
1264 self.keys.insert(event_id, loc);
12551265 }
12561266
12571267 /// Insert a sticker
@@ -1280,7 +1290,13 @@ impl RoomInfo {
12801290 ) {
12811291 let source: MediaSource = sticker_content.content.source.clone().into();
12821292 msg.image_preview = Some(source.clone());
1283 previews.register_preview(settings, source, image_preview.size, worker);
1293 previews.register_preview(
1294 settings,
1295 source,
1296 PreviewKind::Message,
1297 image_preview.size,
1298 worker,
1299 );
12841300 }
12851301 },
12861302 MessageLikeEvent::Redacted(ref redaction) => {
@@ -1294,6 +1310,32 @@ impl RoomInfo {
12941310 }
12951311 }
12961312
1313 /// Insert a reaction to a message.
1314 pub fn insert_reaction_with_preview(
1315 &mut self,
1316 react: ReactionEvent,
1317 settings: &ApplicationSettings,
1318 previews: &mut PreviewManager,
1319 worker: &Requester,
1320 ) {
1321 let MessageLikeEvent::Original(ref orig_react) = react else {
1322 return;
1323 };
1324 let image_uri = OwnedMxcUri::from(orig_react.content.relates_to.key.as_str());
1325 let source = if image_uri.is_valid() && settings.tunables.image_preview.is_some() {
1326 Some(MediaSource::Plain(image_uri))
1327 } else {
1328 None
1329 };
1330
1331 self.insert_reaction(react, source.clone());
1332
1333 if let (Some(source), Some(_)) = (source, &settings.tunables.image_preview) {
1334 let size = ImagePreviewSize { width: 2, height: 1 };
1335 previews.register_preview(settings, source, PreviewKind::Reaction, size, worker);
1336 }
1337 }
1338
12971339 /// Insert an edit.
12981340 fn insert_edit(
12991341 &mut self,
@@ -1443,7 +1485,13 @@ impl RoomInfo {
14431485 (self.get_event_mut(&event_id), &settings.tunables.image_preview)
14441486 {
14451487 msg.image_preview = Some(source.clone());
1446 previews.register_preview(settings, source, image_preview.size, worker)
1488 previews.register_preview(
1489 settings,
1490 source,
1491 PreviewKind::Message,
1492 image_preview.size,
1493 worker,
1494 )
14471495 }
14481496 }
14491497
@@ -1616,7 +1664,7 @@ impl RoomInfo {
16161664 if let Some(reactions) = self.reactions.get(event_id) {
16171665 reactions
16181666 .values()
1619 .any(|(annotation, user)| annotation == emoji && user == user_id)
1667 .any(|(annotation, user, _)| annotation == emoji && user == user_id)
16201668 } else {
16211669 false
16221670 }
@@ -2435,7 +2483,7 @@ pub mod tests {
24352483 for i in 0..3 {
24362484 let event_id = format!("$house_{i}");
24372485 let react = create_reaction_event(&content, &event_id, "@foo:example.com");
2438 info.insert_reaction(react);
2486 info.insert_reaction(react, None);
24392487 }
24402488
24412489 let content = ReactionEventContent::new(Annotation::new(
@@ -2446,19 +2494,21 @@ pub mod tests {
24462494 for i in 0..2 {
24472495 let event_id = format!("$smile_{i}");
24482496 let react = create_reaction_event(&content, &event_id, "@foo:example.com");
2449 info.insert_reaction(react);
2497 info.insert_reaction(react, None);
24502498 }
24512499
24522500 for i in 2..4 {
24532501 let event_id = format!("$smile2_{i}");
24542502 let react = create_reaction_event(&content, &event_id, "@bar:example.com");
2455 info.insert_reaction(react);
2503 info.insert_reaction(react, None);
24562504 }
24572505
2458 assert_eq!(info.get_reactions(&owned_event_id!("$my_reaction")), vec![
2459 ("🏠", 1),
2460 ("🙂", 2)
2461 ]);
2506 let reacts: Vec<_> = info
2507 .get_reactions(&owned_event_id!("$my_reaction"))
2508 .into_iter()
2509 .map(|(key, count, _)| (key, count))
2510 .collect();
2511 assert_eq!(reacts, vec![("🏠", 1), ("🙂", 2)]);
24622512 }
24632513
24642514 #[test]
src/config.rs +5
@@ -14,6 +14,7 @@ use std::str::FromStr;
1414use clap::Parser;
1515use matrix_sdk::EncryptionState;
1616use matrix_sdk::authentication::matrix::MatrixSession;
17use matrix_sdk::media::MediaRetentionPolicy;
1718use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue};
1819use matrix_sdk::ruma::{OwnedDeviceId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId};
1920use ratatui::style::{Color, Modifier as StyleModifier, Style};
@@ -837,6 +838,7 @@ pub struct TunableValues {
837838 pub members_split: Option<SplitDirection>,
838839 pub default_split: SplitDirection,
839840 pub ssl_verify: bool,
841 pub cache_policy: MediaRetentionPolicy,
840842}
841843
842844#[derive(Clone, Debug, Default, Deserialize)]
@@ -886,6 +888,7 @@ pub struct Tunables {
886888 pub members_split: Option<SplitDirection>,
887889 pub default_split: Option<SplitDirection>,
888890 pub ssl_verify: Option<bool>,
891 pub cache_policy: Option<MediaRetentionPolicy>,
889892}
890893
891894impl Tunables {
@@ -934,6 +937,7 @@ impl Tunables {
934937 members_split: self.members_split.or(other.members_split),
935938 default_split: self.default_split.or(other.default_split),
936939 ssl_verify: self.ssl_verify.or(other.ssl_verify),
940 cache_policy: self.cache_policy.or(other.cache_policy),
937941 }
938942 }
939943
@@ -974,6 +978,7 @@ impl Tunables {
974978 members_split: self.members_split,
975979 default_split: self.default_split.unwrap_or_default(),
976980 ssl_verify: self.ssl_verify.unwrap_or(true),
981 cache_policy: self.cache_policy.unwrap_or_default(),
977982 }
978983 }
979984}
src/message/mod.rs +53 −15
@@ -63,7 +63,7 @@ use ratatui_image::protocol::Protocol;
6363
6464use crate::base::MessageEdits;
6565use crate::config::ImagePreviewSize;
66use crate::preview::{ImageStatus, PreviewManager};
66use crate::preview::{ImageStatus, PreviewKind, PreviewManager};
6767use crate::{
6868 base::RoomInfo,
6969 config::ApplicationSettings,
@@ -858,16 +858,37 @@ impl<'a> MessageFormatter<'a> {
858858 proto
859859 }
860860
861 fn push_reactions(&mut self, counts: Vec<(&'a str, usize)>, style: Style, text: &mut Text<'a>) {
861 fn push_reactions(
862 &mut self,
863 counts: Vec<(&'a str, usize, &'a Option<MediaSource>)>,
864 style: Style,
865 text: &mut Text<'a>,
866 settings: &ApplicationSettings,
867 previews: &'a PreviewManager,
868 ) -> Vec<ProtocolPreview<'a>> {
862869 let mut emojis = printer::TextPrinter::new(self.width(), style, self.settings);
863870 let mut reactions = 0;
871 let mut protos = Vec::new();
864872
865 for (key, count) in counts {
873 for (key, count, source) in counts {
866874 if reactions != 0 {
867875 emojis.push_str(" ", style);
868876 }
869877
870 let name = if self.settings.tunables.reaction_shortcode_display {
878 let proto = match source
879 .as_ref()
880 .and_then(|source| previews.get(source, PreviewKind::Reaction))
881 {
882 Some(ImageStatus::Loaded(backend)) => Some(Some(backend)),
883 // Use empty space as placeholder
884 Some(ImageStatus::Queued(_)) | Some(ImageStatus::Downloading(_)) => Some(None),
885 // Fall back to text
886 None | Some(ImageStatus::Error(_)) => None,
887 };
888
889 let name = if proto.is_some() {
890 " "
891 } else if self.settings.tunables.reaction_shortcode_display {
871892 if let Some(emoji) = emojis::get(key) {
872893 if let Some(short) = emoji.shortcode() {
873894 short
@@ -886,6 +907,13 @@ impl<'a> MessageFormatter<'a> {
886907 };
887908
888909 emojis.push_str("[", style);
910 if let Some(Some(proto)) = proto {
911 let (x, y) = emojis.cursor_pos();
912 let y = (y + text.lines.len()) as u16;
913 let x = x as u16 + self.cols.user_gutter_width(settings);
914
915 protos.push((proto, x, y));
916 }
889917 emojis.push_str(name, style);
890918 emojis.push_str(" ", style);
891919 emojis.push_span_nobreak(Span::styled(count.to_string(), style));
@@ -897,6 +925,8 @@ impl<'a> MessageFormatter<'a> {
897925 if reactions > 0 {
898926 self.push_text(emojis.finish(), style, text);
899927 }
928
929 protos
900930 }
901931
902932 fn push_thread_reply_count(&mut self, len: usize, text: &mut Text<'a>) {
@@ -1077,7 +1107,7 @@ impl Message {
10771107 info: &'a RoomInfo,
10781108 settings: &'a ApplicationSettings,
10791109 previews: &'a PreviewManager,
1080 ) -> (Text<'a>, [Option<ProtocolPreview<'a>>; 2]) {
1110 ) -> (Text<'a>, Vec<ProtocolPreview<'a>>) {
10811111 let width = vwctx.get_width();
10821112
10831113 let style = self.get_render_style(selected, settings);
@@ -1085,12 +1115,17 @@ impl Message {
10851115 let mut text = Text::default();
10861116 let width = fmt.width();
10871117
1118 let mut protos = Vec::new();
1119
10881120 // Show the message that this one replied to, if any.
10891121 let reply = self.reply_to().or_else(|| self.thread_root()).map(|e| info.get_event(&e));
1090 let proto_reply = reply.as_ref().and_then(|r| {
1122 if let Some(r) = reply {
10911123 if let Some(r) = r {
10921124 // Format the reply header, push it into the `Text` buffer, and get any image.
1093 fmt.push_in_reply(r, style, &mut text, info, settings, previews)
1125 let proto_reply = fmt.push_in_reply(r, style, &mut text, info, settings, previews);
1126 if let Some(proto) = proto_reply {
1127 protos.push(proto)
1128 }
10941129 } else {
10951130 fmt.push_spans(
10961131 Line::from(vec![
@@ -1102,22 +1137,21 @@ impl Message {
11021137 style,
11031138 &mut text,
11041139 );
1105 None
11061140 }
1107 });
1141 }
11081142
11091143 // Now show the message contents, and the inlined reply if we couldn't find it above.
11101144 let (msg, proto) = self.show_msg(width, style, settings, previews);
11111145
11121146 // Given our text so far, determine the image offset.
1113 let proto_main = proto.map(|p| {
1147 if let Some(p) = proto {
11141148 let y_off = text.lines.len() as u16;
11151149 let x_off = fmt.cols.user_gutter_width(settings);
11161150
11171151 // Account for extra lines printed before the message;
11181152 let y_off = y_off + fmt.message_start_line();
1119 (p, x_off, y_off)
1120 });
1153 protos.push((p, x_off, y_off));
1154 }
11211155
11221156 fmt.push_text(msg, style, &mut text);
11231157
@@ -1140,14 +1174,15 @@ impl Message {
11401174 if settings.tunables.reaction_display {
11411175 let reactions =
11421176 self.event.event_id().map(|id| info.get_reactions(id)).unwrap_or_default();
1143 fmt.push_reactions(reactions, style, &mut text);
1177 let react_protos = fmt.push_reactions(reactions, style, &mut text, settings, previews);
1178 protos.extend(react_protos);
11441179 }
11451180
11461181 if let Some(thread) = self.event.event_id().and_then(|id| info.get_thread(Some(id))) {
11471182 fmt.push_thread_reply_count(thread.len(), &mut text);
11481183 }
11491184
1150 (text, [proto_main, proto_reply])
1185 (text, protos)
11511186 }
11521187
11531188 pub fn show<'a>(
@@ -1170,7 +1205,10 @@ impl Message {
11701205 previews: &'a PreviewManager,
11711206 ) -> (Text<'a>, Option<&'a Protocol>) {
11721207 let mut proto = None;
1173 let placeholder = match self.image_preview.as_ref().and_then(|source| previews.get(source))
1208 let placeholder = match self
1209 .image_preview
1210 .as_ref()
1211 .and_then(|source| previews.get(source, PreviewKind::Message))
11741212 {
11751213 None => None,
11761214 Some(ImageStatus::Queued(image_preview_size)) => {
src/message/printer.rs +5
@@ -50,6 +50,11 @@ impl<'a> TextPrinter<'a> {
5050 }
5151 }
5252
53 /// The `(x, y)` position where the next text will be printed.
54 pub fn cursor_pos(&self) -> (usize, usize) {
55 (self.curr_width, self.text.lines.len().saturating_sub(1))
56 }
57
5358 /// Configure the alignment for each line.
5459 pub fn align(mut self, alignment: Alignment) -> Self {
5560 self.alignment = alignment;
src/preview.rs +19 −10
@@ -31,6 +31,12 @@ pub enum ImageStatus {
3131 Error(String),
3232}
3333
34#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
35pub enum PreviewKind {
36 Message,
37 Reaction,
38}
39
3440pub struct PreviewManager {
3541 /// Image preview "protocol" picker.
3642 picker: Option<Arc<Picker>>,
@@ -39,7 +45,7 @@ pub struct PreviewManager {
3945 permits: Arc<Semaphore>,
4046
4147 /// Indexed by [`MediaSource::unique_key`]
42 previews: HashMap<String, ImageStatus>,
48 previews: HashMap<(String, PreviewKind), ImageStatus>,
4349}
4450
4551impl PreviewManager {
@@ -51,17 +57,17 @@ impl PreviewManager {
5157 }
5258 }
5359
54 pub fn get(&self, source: &MediaSource) -> Option<&ImageStatus> {
55 self.previews.get(&source.unique_key())
60 pub fn get(&self, source: &MediaSource, kind: PreviewKind) -> Option<&ImageStatus> {
61 self.previews.get(&(source.unique_key(), kind))
5662 }
5763
58 fn insert(&mut self, key: String, status: ImageStatus) {
59 self.previews.insert(key, status);
64 fn insert(&mut self, key: String, kind: PreviewKind, status: ImageStatus) {
65 self.previews.insert((key, kind), status);
6066 }
6167
6268 /// Queue download and preparation of preview
63 pub fn load(&mut self, source: &MediaSource, worker: &Requester) {
64 let Some(status) = self.previews.get_mut(&source.unique_key()) else {
69 pub fn load(&mut self, source: &MediaSource, kind: PreviewKind, worker: &Requester) {
70 let Some(status) = self.previews.get_mut(&(source.unique_key(), kind)) else {
6571 return;
6672 };
6773 let Some(picker) = &self.picker else { return };
@@ -72,6 +78,7 @@ impl PreviewManager {
7278
7379 worker.load_image(
7480 source.to_owned(),
81 kind,
7582 size.to_owned(),
7683 Arc::clone(picker),
7784 Arc::clone(&self.permits),
@@ -83,6 +90,7 @@ impl PreviewManager {
8390 &mut self,
8491 settings: &ApplicationSettings,
8592 source: MediaSource,
93 kind: PreviewKind,
8694 size: ImagePreviewSize,
8795 worker: &Requester,
8896 ) {
@@ -90,7 +98,7 @@ impl PreviewManager {
9098 return;
9199 }
92100
93 let key = source.unique_key();
101 let key = (source.unique_key(), kind);
94102 if self.previews.contains_key(&key) {
95103 return;
96104 }
@@ -102,7 +110,7 @@ impl PreviewManager {
102110 .as_ref()
103111 .is_some_and(|setting| !setting.lazy_load)
104112 {
105 self.load(&source, worker);
113 self.load(&source, kind, worker);
106114 }
107115 }
108116}
@@ -133,6 +141,7 @@ pub async fn load_image(
133141 store: AsyncProgramStore,
134142 media: Media,
135143 source: MediaSource,
144 kind: PreviewKind,
136145 picker: Arc<Picker>,
137146 permits: Arc<Semaphore>,
138147 size: ImagePreviewSize,
@@ -178,5 +187,5 @@ pub async fn load_image(
178187 };
179188
180189 let mut locked = store.lock().await;
181 locked.application.previews.insert(key, status);
190 locked.application.previews.insert(key, kind, status);
182191}
src/tests.rs +1
@@ -208,6 +208,7 @@ pub fn mock_tunables() -> TunableValues {
208208 members_split: Default::default(),
209209 default_split: Default::default(),
210210 ssl_verify: true,
211 cache_policy: Default::default(),
211212 }
212213}
213214
src/windows/room/chat.rs +13 −12
@@ -542,21 +542,22 @@ impl ChatState {
542542 None => return Ok(None),
543543 };
544544
545 let reactions = reactions.iter().filter_map(|(event_id, (reaction, user_id))| {
546 if user_id != &settings.profile.user_id {
547 return None;
548 }
545 let reactions =
546 reactions.iter().filter_map(|(event_id, (reaction, user_id, _))| {
547 if user_id != &settings.profile.user_id {
548 return None;
549 }
549550
550 if let Some(emoji) = &emoji {
551 if emoji == reaction {
552 return Some(event_id);
551 if let Some(emoji) = &emoji {
552 if emoji == reaction {
553 return Some(event_id);
554 } else {
555 return None;
556 }
553557 } else {
554 return None;
558 return Some(event_id);
555559 }
556 } else {
557 return Some(event_id);
558 }
559 });
560 });
560561
561562 for reaction in reactions {
562563 let _ = room.redact(reaction, None, None).await.map_err(IambError::from)?;
src/windows/room/scrollback.rs +28 −25
@@ -55,7 +55,7 @@ use crate::{
5555 },
5656 config::ApplicationSettings,
5757 message::{Message, MessageCursor, MessageKey, Messages},
58 preview::PreviewManager,
58 preview::{PreviewKind, PreviewManager},
5959};
6060
6161fn no_msgs() -> EditError<IambInfo> {
@@ -1364,12 +1364,13 @@ impl StatefulWidget for Scrollback<'_> {
13641364 let mut prev = prevmsg(&corner_key, thread);
13651365
13661366 // load image previews
1367 for (_, item) in thread.range(&corner_key..).rev() {
1367 for (key, item) in thread.range(&corner_key..).rev() {
13681368 if let Some(source) = &item.image_preview {
1369 self.store
1370 .application
1371 .previews
1372 .load(source, &self.store.application.worker);
1369 self.store.application.previews.load(
1370 source,
1371 PreviewKind::Message,
1372 &self.store.application.worker,
1373 );
13731374 }
13741375 let reply = item
13751376 .reply_to()
@@ -1377,10 +1378,20 @@ impl StatefulWidget for Scrollback<'_> {
13771378 .and_then(|e| info.get_event(&e))
13781379 .and_then(|msg| msg.image_preview.as_ref());
13791380 if let Some(source) = reply {
1380 self.store
1381 .application
1382 .previews
1383 .load(source, &self.store.application.worker);
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(
1390 source,
1391 PreviewKind::Reaction,
1392 &self.store.application.worker,
1393 );
1394 }
13841395 }
13851396 }
13861397
@@ -1388,7 +1399,7 @@ impl StatefulWidget for Scrollback<'_> {
13881399 for (key, item) in thread.range(&corner_key..) {
13891400 let sel = key == cursor_key;
13901401
1391 let (txt, [mut msg_preview, mut reply_preview]) =
1402 let (txt, mut msg_previews) =
13921403 item.show_with_preview(prev, foc && sel, &state.viewctx, info, settings, previews);
13931404
13941405 let incomplete_ok = !full || !sel;
@@ -1405,17 +1416,9 @@ impl StatefulWidget for Scrollback<'_> {
14051416 continue;
14061417 }
14071418
1408 // Only take the preview into the matching row number.
1409 // `reply` and `msg` previews are on rows,
1410 // so an `or` works to pick the one that matches (if any)
1411 let line_preview = match msg_preview {
1412 Some((_, _, y)) if y as usize == row => msg_preview.take(),
1413 _ => None,
1414 }
1415 .or(match reply_preview {
1416 Some((_, _, y)) if y as usize == row => reply_preview.take(),
1417 _ => None,
1418 });
1419 // Only take the previews into the matching row number.
1420 let line_preview: Vec<_> =
1421 msg_previews.extract_if(.., |(_, _, y)| *y as usize == row).collect();
14191422
14201423 lines.push((key, row, line, line_preview));
14211424 sawit |= sel;
@@ -1440,9 +1443,9 @@ impl StatefulWidget for Scrollback<'_> {
14401443 let mut image_previews = vec![];
14411444 for (_, _, txt, line_preview) in lines.into_iter() {
14421445 let _ = buf.set_line(x, y, &txt, area.width);
1443 if let Some((backend, msg_x, _)) = line_preview {
1444 image_previews.push((x + msg_x, y, backend));
1445 }
1446 image_previews.extend(
1447 line_preview.into_iter().map(|(backend, msg_x, _)| (x + msg_x, y, backend)),
1448 );
14461449
14471450 y += 1;
14481451 }
src/worker.rs +33 −10
@@ -98,7 +98,7 @@ use crate::base::{EchoLocation, MessageNeed};
9898use crate::config::{ImagePreviewSize, ProxyUrl};
9999use crate::message::{Message, MessageEvent, MessageId, MessageKey};
100100use crate::notifications::register_notifications;
101use crate::preview::load_image;
101use crate::preview::PreviewKind;
102102use crate::{
103103 ApplicationSettings,
104104 base::{
@@ -326,7 +326,7 @@ fn load_insert(
326326 info.insert_with_preview(msg, settings, previews, worker);
327327 },
328328 AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Reaction(ev)) => {
329 info.insert_reaction(ev);
329 info.insert_reaction_with_preview(ev, settings, previews, worker);
330330 },
331331 AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Sticker(ev)) => {
332332 info.insert_sticker(ev, settings, previews, worker);
@@ -726,7 +726,7 @@ pub enum WorkerTask {
726726 TypingNotice(OwnedRoomId),
727727 Verify(VerifyAction, SasVerification, ClientReply<IambResult<EditInfo>>),
728728 VerifyRequest(OwnedUserId, ClientReply<IambResult<EditInfo>>),
729 LoadImage(MediaSource, ImagePreviewSize, Arc<Picker>, Arc<Semaphore>),
729 LoadImage(MediaSource, PreviewKind, ImagePreviewSize, Arc<Picker>, Arc<Semaphore>),
730730}
731731
732732impl Debug for WorkerTask {
@@ -790,9 +790,10 @@ impl Debug for WorkerTask {
790790 .field(&format_args!("_"))
791791 .finish()
792792 },
793 WorkerTask::LoadImage(source, size, _, _) => {
793 WorkerTask::LoadImage(source, kind, size, _, _) => {
794794 f.debug_tuple("WorkerTask::RenderImage")
795795 .field(source)
796 .field(kind)
796797 .field(size)
797798 .field(&format_args!("_"))
798799 .field(&format_args!("_"))
@@ -845,7 +846,10 @@ async fn create_client_inner(
845846
846847 let http = builder.build().map_err(matrix_sdk::HttpError::Reqwest)?;
847848
848 let req_config = RequestConfig::new().timeout(req_timeout).max_retry_time(req_timeout);
849 let req_config = RequestConfig::new()
850 .timeout(req_timeout)
851 .max_retry_time(req_timeout)
852 .retry_limit(8);
849853
850854 // Set up the Matrix client for the selected profile.
851855 let builder = Client::builder()
@@ -881,6 +885,12 @@ pub async fn create_client(settings: &ApplicationSettings) -> Client {
881885
882886 client.event_cache().subscribe().expect("Failed to start event cache");
883887
888 client
889 .media()
890 .set_media_retention_policy(settings.tunables.cache_policy)
891 .await
892 .expect("Failed to start event cache");
893
884894 client
885895}
886896
@@ -978,11 +988,14 @@ impl Requester {
978988 pub fn load_image(
979989 &self,
980990 source: MediaSource,
991 kind: PreviewKind,
981992 size: ImagePreviewSize,
982993 picker: Arc<Picker>,
983994 permits: Arc<Semaphore>,
984995 ) {
985 self.tx.send(WorkerTask::LoadImage(source, size, picker, permits)).unwrap();
996 self.tx
997 .send(WorkerTask::LoadImage(source, kind, size, picker, permits))
998 .unwrap();
986999 }
9871000}
9881001
@@ -1081,12 +1094,13 @@ impl ClientWorker {
10811094 assert!(self.initialized);
10821095 reply.send(self.verify_request(user_id).await);
10831096 },
1084 WorkerTask::LoadImage(source, size, picker, permits) => {
1097 WorkerTask::LoadImage(source, kind, size, picker, permits) => {
10851098 assert!(self.initialized);
1086 tokio::spawn(load_image(
1099 tokio::spawn(crate::preview::load_image(
10871100 self.store.clone().unwrap(),
10881101 self.client.media(),
10891102 source,
1103 kind,
10901104 picker,
10911105 permits,
10921106 size,
@@ -1188,9 +1202,18 @@ impl ClientWorker {
11881202 let sender = ev.sender().to_owned();
11891203 let _ = locked.application.presences.get_or_default(sender);
11901204
1191 let info = locked.application.get_room_info(room_id.to_owned());
1205 let ChatStore { rooms, previews, settings, worker, .. } =
1206 &mut locked.application;
1207 let info = rooms.get_or_default(room_id.to_owned());
1208
11921209 update_event_receipts(info, &room, ev.event_id()).await;
1193 info.insert_reaction(ev.into_full_event(room_id.to_owned()));
1210
1211 info.insert_reaction_with_preview(
1212 ev.into_full_event(room_id.to_owned()),
1213 settings,
1214 previews,
1215 worker,
1216 );
11941217 }
11951218 },
11961219 );