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
126key and can be overridden as described in 126key and can be overridden as described in
127.Sx PROFILES . 127.Sx PROFILES .
128.Bl -tag -width Ds 128.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
129.It Sy default_markup 135.It Sy default_markup
130Controls how text in the message bar is interpreted by default. 136Controls how text in the message bar is interpreted by default.
131Possible values are 137Possible values are
src/base.rs +83 −33
@@ -13,6 +13,7 @@ use std::time::{Duration, Instant};
13 13
14use emojis::Emoji; 14use emojis::Emoji;
15 15
16use matrix_sdk::ruma::OwnedMxcUri;
16use matrix_sdk::ruma::OwnedTransactionId; 17use matrix_sdk::ruma::OwnedTransactionId;
17use matrix_sdk::ruma::events::receipt::ReceiptThread; 18use matrix_sdk::ruma::events::receipt::ReceiptThread;
18use matrix_sdk::ruma::events::room::MediaSource; 19use matrix_sdk::ruma::events::room::MediaSource;
@@ -93,6 +94,8 @@ use modalkit::{
93 prelude::{CommandType, WordStyle}, 94 prelude::{CommandType, WordStyle},
94}; 95};
95 96
97use crate::config::ImagePreviewSize;
98use crate::preview::PreviewKind;
96use crate::{ 99use crate::{
97 config::{ApplicationSettings, ImagePreviewProtocolValues}, 100 config::{ApplicationSettings, ImagePreviewProtocolValues},
98 message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages}, 101 message::{Message, MessageEvent, MessageKey, MessageTimeStamp, Messages},
@@ -702,7 +705,7 @@ pub type IambResult<T> = UIResult<T, IambInfo>;
702/// 705///
703/// The event identifier used as a key here is the ID for the reaction, and not for the message 706/// The event identifier used as a key here is the ID for the reaction, and not for the message
704/// it's reacting to. 707/// it's reacting to.
705pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId)>; 708pub type MessageReactions = HashMap<OwnedEventId, (String, OwnedUserId, Option<MediaSource>)>;
706 709
707pub type MessageEdits = BTreeMap<MessageKey, RoomMessageEventContentWithoutRelation>; 710pub type MessageEdits = BTreeMap<MessageKey, RoomMessageEventContentWithoutRelation>;
708 711
@@ -1133,22 +1136,25 @@ impl RoomInfo {
1133 } 1136 }
1134 1137
1135 /// Get the reactions and their counts for a message. 1138 /// 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>)> {
1137 if let Some(reacts) = self.reactions.get(event_id) { 1140 if let Some(reacts) = self.reactions.get(event_id) {
1138 let mut counts = HashMap::new(); 1141 let mut counts = HashMap::new();
1139 1142
1140 let mut seen_user_reactions = BTreeSet::new(); 1143 let mut seen_user_reactions = BTreeSet::new();
1141 1144
1142 for (key, user) in reacts.values() { 1145 for (key, user, source) in reacts.values() {
1143 if !seen_user_reactions.contains(&(key, user)) { 1146 if !seen_user_reactions.contains(&(key, user)) {
1144 seen_user_reactions.insert((key, user)); 1147 seen_user_reactions.insert((key, user));
1145 let count = counts.entry(key.as_str()).or_default(); 1148 let count = counts.entry(key.as_str()).or_insert((0, source));
1146 *count += 1; 1149 count.0 += 1;
1147 } 1150 }
1148 } 1151 }
1149 1152
1150 let mut reactions = counts.into_iter().collect::<Vec<_>>(); 1153 let mut reactions = counts
1151 reactions.sort(); 1154 .into_iter()
1155 .map(|(key, (count, source))| (key, count, source))
1156 .collect::<Vec<_>>();
1157 reactions.sort_by_key(|item| (item.0, item.1));
1152 1158
1153 reactions 1159 reactions
1154 } else { 1160 } else {
@@ -1156,6 +1162,14 @@ impl RoomInfo {
1156 } 1162 }
1157 } 1163 }
1158 1164
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
1159 /// Map an event identifier to its [MessageKey]. 1173 /// Map an event identifier to its [MessageKey].
1160 pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> { 1174 pub fn get_message_key(&self, event_id: &EventId) -> Option<&MessageKey> {
1161 self.keys.get(event_id)?.to_message_key() 1175 self.keys.get(event_id)?.to_message_key()
@@ -1233,25 +1247,21 @@ impl RoomInfo {
1233 } 1247 }
1234 1248
1235 /// Insert a reaction to a message. 1249 /// Insert a reaction to a message.
1236 pub fn insert_reaction(&mut self, react: ReactionEvent) { 1250 fn insert_reaction(&mut self, react: ReactionEvent, source: Option<MediaSource>) {
1237 match react { 1251 let MessageLikeEvent::Original(react) = react else {
1238 MessageLikeEvent::Original(react) => { 1252 return;
1239 let rel_id = react.content.relates_to.event_id; 1253 };
1240 let key = react.content.relates_to.key; 1254 let rel_id = react.content.relates_to.event_id;
1255 let key = react.content.relates_to.key;
1241 1256
1242 let message = self.reactions.entry(rel_id.clone()).or_default(); 1257 let message = self.reactions.entry(rel_id.clone()).or_default();
1243 let event_id = react.event_id; 1258 let event_id = react.event_id;
1244 let user_id = react.sender; 1259 let user_id = react.sender;
1245 1260
1246 message.insert(event_id.clone(), (key, user_id)); 1261 message.insert(event_id.clone(), (key, user_id, source));
1247 1262
1248 let loc = EventLocation::Reaction(rel_id); 1263 let loc = EventLocation::Reaction(rel_id);
1249 self.keys.insert(event_id, loc); 1264 self.keys.insert(event_id, loc);
1250 },
1251 MessageLikeEvent::Redacted(_) => {
1252 return;
1253 },
1254 }
1255 } 1265 }
1256 1266
1257 /// Insert a sticker 1267 /// Insert a sticker
@@ -1280,7 +1290,13 @@ impl RoomInfo {
1280 ) { 1290 ) {
1281 let source: MediaSource = sticker_content.content.source.clone().into(); 1291 let source: MediaSource = sticker_content.content.source.clone().into();
1282 msg.image_preview = Some(source.clone()); 1292 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 );
1284 } 1300 }
1285 }, 1301 },
1286 MessageLikeEvent::Redacted(ref redaction) => { 1302 MessageLikeEvent::Redacted(ref redaction) => {
@@ -1294,6 +1310,32 @@ impl RoomInfo {
1294 } 1310 }
1295 } 1311 }
1296 1312
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
1297 /// Insert an edit. 1339 /// Insert an edit.
1298 fn insert_edit( 1340 fn insert_edit(
1299 &mut self, 1341 &mut self,
@@ -1443,7 +1485,13 @@ impl RoomInfo {
1443 (self.get_event_mut(&event_id), &settings.tunables.image_preview) 1485 (self.get_event_mut(&event_id), &settings.tunables.image_preview)
1444 { 1486 {
1445 msg.image_preview = Some(source.clone()); 1487 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 )
1447 } 1495 }
1448 } 1496 }
1449 1497
@@ -1616,7 +1664,7 @@ impl RoomInfo {
1616 if let Some(reactions) = self.reactions.get(event_id) { 1664 if let Some(reactions) = self.reactions.get(event_id) {
1617 reactions 1665 reactions
1618 .values() 1666 .values()
1619 .any(|(annotation, user)| annotation == emoji && user == user_id) 1667 .any(|(annotation, user, _)| annotation == emoji && user == user_id)
1620 } else { 1668 } else {
1621 false 1669 false
1622 } 1670 }
@@ -2435,7 +2483,7 @@ pub mod tests {
2435 for i in 0..3 { 2483 for i in 0..3 {
2436 let event_id = format!("$house_{i}"); 2484 let event_id = format!("$house_{i}");
2437 let react = create_reaction_event(&content, &event_id, "@foo:example.com"); 2485 let react = create_reaction_event(&content, &event_id, "@foo:example.com");
2438 info.insert_reaction(react); 2486 info.insert_reaction(react, None);
2439 } 2487 }
2440 2488
2441 let content = ReactionEventContent::new(Annotation::new( 2489 let content = ReactionEventContent::new(Annotation::new(
@@ -2446,19 +2494,21 @@ pub mod tests {
2446 for i in 0..2 { 2494 for i in 0..2 {
2447 let event_id = format!("$smile_{i}"); 2495 let event_id = format!("$smile_{i}");
2448 let react = create_reaction_event(&content, &event_id, "@foo:example.com"); 2496 let react = create_reaction_event(&content, &event_id, "@foo:example.com");
2449 info.insert_reaction(react); 2497 info.insert_reaction(react, None);
2450 } 2498 }
2451 2499
2452 for i in 2..4 { 2500 for i in 2..4 {
2453 let event_id = format!("$smile2_{i}"); 2501 let event_id = format!("$smile2_{i}");
2454 let react = create_reaction_event(&content, &event_id, "@bar:example.com"); 2502 let react = create_reaction_event(&content, &event_id, "@bar:example.com");
2455 info.insert_reaction(react); 2503 info.insert_reaction(react, None);
2456 } 2504 }
2457 2505
2458 assert_eq!(info.get_reactions(&owned_event_id!("$my_reaction")), vec![ 2506 let reacts: Vec<_> = info
2459 ("🏠", 1), 2507 .get_reactions(&owned_event_id!("$my_reaction"))
2460 ("🙂", 2) 2508 .into_iter()
2461 ]); 2509 .map(|(key, count, _)| (key, count))
2510 .collect();
2511 assert_eq!(reacts, vec![("🏠", 1), ("🙂", 2)]);
2462 } 2512 }
2463 2513
2464 #[test] 2514 #[test]
src/config.rs +5
@@ -14,6 +14,7 @@ use std::str::FromStr;
14use clap::Parser; 14use clap::Parser;
15use matrix_sdk::EncryptionState; 15use matrix_sdk::EncryptionState;
16use matrix_sdk::authentication::matrix::MatrixSession; 16use matrix_sdk::authentication::matrix::MatrixSession;
17use matrix_sdk::media::MediaRetentionPolicy;
17use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue}; 18use matrix_sdk::reqwest::header::{HeaderMap, HeaderValue};
18use matrix_sdk::ruma::{OwnedDeviceId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId}; 19use matrix_sdk::ruma::{OwnedDeviceId, OwnedRoomAliasId, OwnedRoomId, OwnedUserId, UserId};
19use ratatui::style::{Color, Modifier as StyleModifier, Style}; 20use ratatui::style::{Color, Modifier as StyleModifier, Style};
@@ -837,6 +838,7 @@ pub struct TunableValues {
837 pub members_split: Option<SplitDirection>, 838 pub members_split: Option<SplitDirection>,
838 pub default_split: SplitDirection, 839 pub default_split: SplitDirection,
839 pub ssl_verify: bool, 840 pub ssl_verify: bool,
841 pub cache_policy: MediaRetentionPolicy,
840} 842}
841 843
842#[derive(Clone, Debug, Default, Deserialize)] 844#[derive(Clone, Debug, Default, Deserialize)]
@@ -886,6 +888,7 @@ pub struct Tunables {
886 pub members_split: Option<SplitDirection>, 888 pub members_split: Option<SplitDirection>,
887 pub default_split: Option<SplitDirection>, 889 pub default_split: Option<SplitDirection>,
888 pub ssl_verify: Option<bool>, 890 pub ssl_verify: Option<bool>,
891 pub cache_policy: Option<MediaRetentionPolicy>,
889} 892}
890 893
891impl Tunables { 894impl Tunables {
@@ -934,6 +937,7 @@ impl Tunables {
934 members_split: self.members_split.or(other.members_split), 937 members_split: self.members_split.or(other.members_split),
935 default_split: self.default_split.or(other.default_split), 938 default_split: self.default_split.or(other.default_split),
936 ssl_verify: self.ssl_verify.or(other.ssl_verify), 939 ssl_verify: self.ssl_verify.or(other.ssl_verify),
940 cache_policy: self.cache_policy.or(other.cache_policy),
937 } 941 }
938 } 942 }
939 943
@@ -974,6 +978,7 @@ impl Tunables {
974 members_split: self.members_split, 978 members_split: self.members_split,
975 default_split: self.default_split.unwrap_or_default(), 979 default_split: self.default_split.unwrap_or_default(),
976 ssl_verify: self.ssl_verify.unwrap_or(true), 980 ssl_verify: self.ssl_verify.unwrap_or(true),
981 cache_policy: self.cache_policy.unwrap_or_default(),
977 } 982 }
978 } 983 }
979} 984}
src/message/mod.rs +53 −15
@@ -63,7 +63,7 @@ use ratatui_image::protocol::Protocol;
63 63
64use crate::base::MessageEdits; 64use crate::base::MessageEdits;
65use crate::config::ImagePreviewSize; 65use crate::config::ImagePreviewSize;
66use crate::preview::{ImageStatus, PreviewManager}; 66use crate::preview::{ImageStatus, PreviewKind, PreviewManager};
67use crate::{ 67use crate::{
68 base::RoomInfo, 68 base::RoomInfo,
69 config::ApplicationSettings, 69 config::ApplicationSettings,
@@ -858,16 +858,37 @@ impl<'a> MessageFormatter<'a> {
858 proto 858 proto
859 } 859 }
860 860
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>> {
862 let mut emojis = printer::TextPrinter::new(self.width(), style, self.settings); 869 let mut emojis = printer::TextPrinter::new(self.width(), style, self.settings);
863 let mut reactions = 0; 870 let mut reactions = 0;
871 let mut protos = Vec::new();
864 872
865 for (key, count) in counts { 873 for (key, count, source) in counts {
866 if reactions != 0 { 874 if reactions != 0 {
867 emojis.push_str(" ", style); 875 emojis.push_str(" ", style);
868 } 876 }
869 877
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 {
871 if let Some(emoji) = emojis::get(key) { 892 if let Some(emoji) = emojis::get(key) {
872 if let Some(short) = emoji.shortcode() { 893 if let Some(short) = emoji.shortcode() {
873 short 894 short
@@ -886,6 +907,13 @@ impl<'a> MessageFormatter<'a> {
886 }; 907 };
887 908
888 emojis.push_str("[", style); 909 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 }
889 emojis.push_str(name, style); 917 emojis.push_str(name, style);
890 emojis.push_str(" ", style); 918 emojis.push_str(" ", style);
891 emojis.push_span_nobreak(Span::styled(count.to_string(), style)); 919 emojis.push_span_nobreak(Span::styled(count.to_string(), style));
@@ -897,6 +925,8 @@ impl<'a> MessageFormatter<'a> {
897 if reactions > 0 { 925 if reactions > 0 {
898 self.push_text(emojis.finish(), style, text); 926 self.push_text(emojis.finish(), style, text);
899 } 927 }
928
929 protos
900 } 930 }
901 931
902 fn push_thread_reply_count(&mut self, len: usize, text: &mut Text<'a>) { 932 fn push_thread_reply_count(&mut self, len: usize, text: &mut Text<'a>) {
@@ -1077,7 +1107,7 @@ impl Message {
1077 info: &'a RoomInfo, 1107 info: &'a RoomInfo,
1078 settings: &'a ApplicationSettings, 1108 settings: &'a ApplicationSettings,
1079 previews: &'a PreviewManager, 1109 previews: &'a PreviewManager,
1080 ) -> (Text<'a>, [Option<ProtocolPreview<'a>>; 2]) { 1110 ) -> (Text<'a>, Vec<ProtocolPreview<'a>>) {
1081 let width = vwctx.get_width(); 1111 let width = vwctx.get_width();
1082 1112
1083 let style = self.get_render_style(selected, settings); 1113 let style = self.get_render_style(selected, settings);
@@ -1085,12 +1115,17 @@ impl Message {
1085 let mut text = Text::default(); 1115 let mut text = Text::default();
1086 let width = fmt.width(); 1116 let width = fmt.width();
1087 1117
1118 let mut protos = Vec::new();
1119
1088 // Show the message that this one replied to, if any. 1120 // Show the message that this one replied to, if any.
1089 let reply = self.reply_to().or_else(|| self.thread_root()).map(|e| info.get_event(&e)); 1121 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 {
1091 if let Some(r) = r { 1123 if let Some(r) = r {
1092 // Format the reply header, push it into the `Text` buffer, and get any image. 1124 // 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 }
1094 } else { 1129 } else {
1095 fmt.push_spans( 1130 fmt.push_spans(
1096 Line::from(vec![ 1131 Line::from(vec![
@@ -1102,22 +1137,21 @@ impl Message {
1102 style, 1137 style,
1103 &mut text, 1138 &mut text,
1104 ); 1139 );
1105 None
1106 } 1140 }
1107 }); 1141 }
1108 1142
1109 // Now show the message contents, and the inlined reply if we couldn't find it above. 1143 // Now show the message contents, and the inlined reply if we couldn't find it above.
1110 let (msg, proto) = self.show_msg(width, style, settings, previews); 1144 let (msg, proto) = self.show_msg(width, style, settings, previews);
1111 1145
1112 // Given our text so far, determine the image offset. 1146 // Given our text so far, determine the image offset.
1113 let proto_main = proto.map(|p| { 1147 if let Some(p) = proto {
1114 let y_off = text.lines.len() as u16; 1148 let y_off = text.lines.len() as u16;
1115 let x_off = fmt.cols.user_gutter_width(settings); 1149 let x_off = fmt.cols.user_gutter_width(settings);
1116 1150
1117 // Account for extra lines printed before the message; 1151 // Account for extra lines printed before the message;
1118 let y_off = y_off + fmt.message_start_line(); 1152 let y_off = y_off + fmt.message_start_line();
1119 (p, x_off, y_off) 1153 protos.push((p, x_off, y_off));
1120 }); 1154 }
1121 1155
1122 fmt.push_text(msg, style, &mut text); 1156 fmt.push_text(msg, style, &mut text);
1123 1157
@@ -1140,14 +1174,15 @@ impl Message {
1140 if settings.tunables.reaction_display { 1174 if settings.tunables.reaction_display {
1141 let reactions = 1175 let reactions =
1142 self.event.event_id().map(|id| info.get_reactions(id)).unwrap_or_default(); 1176 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);
1144 } 1179 }
1145 1180
1146 if let Some(thread) = self.event.event_id().and_then(|id| info.get_thread(Some(id))) { 1181 if let Some(thread) = self.event.event_id().and_then(|id| info.get_thread(Some(id))) {
1147 fmt.push_thread_reply_count(thread.len(), &mut text); 1182 fmt.push_thread_reply_count(thread.len(), &mut text);
1148 } 1183 }
1149 1184
1150 (text, [proto_main, proto_reply]) 1185 (text, protos)
1151 } 1186 }
1152 1187
1153 pub fn show<'a>( 1188 pub fn show<'a>(
@@ -1170,7 +1205,10 @@ impl Message {
1170 previews: &'a PreviewManager, 1205 previews: &'a PreviewManager,
1171 ) -> (Text<'a>, Option<&'a Protocol>) { 1206 ) -> (Text<'a>, Option<&'a Protocol>) {
1172 let mut proto = None; 1207 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))
1174 { 1212 {
1175 None => None, 1213 None => None,
1176 Some(ImageStatus::Queued(image_preview_size)) => { 1214 Some(ImageStatus::Queued(image_preview_size)) => {
src/message/printer.rs +5
@@ -50,6 +50,11 @@ impl<'a> TextPrinter<'a> {
50 } 50 }
51 } 51 }
52 52
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
53 /// Configure the alignment for each line. 58 /// Configure the alignment for each line.
54 pub fn align(mut self, alignment: Alignment) -> Self { 59 pub fn align(mut self, alignment: Alignment) -> Self {
55 self.alignment = alignment; 60 self.alignment = alignment;
src/preview.rs +19 −10
@@ -31,6 +31,12 @@ pub enum ImageStatus {
31 Error(String), 31 Error(String),
32} 32}
33 33
34#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
35pub enum PreviewKind {
36 Message,
37 Reaction,
38}
39
34pub struct PreviewManager { 40pub struct PreviewManager {
35 /// Image preview "protocol" picker. 41 /// Image preview "protocol" picker.
36 picker: Option<Arc<Picker>>, 42 picker: Option<Arc<Picker>>,
@@ -39,7 +45,7 @@ pub struct PreviewManager {
39 permits: Arc<Semaphore>, 45 permits: Arc<Semaphore>,
40 46
41 /// Indexed by [`MediaSource::unique_key`] 47 /// Indexed by [`MediaSource::unique_key`]
42 previews: HashMap<String, ImageStatus>, 48 previews: HashMap<(String, PreviewKind), ImageStatus>,
43} 49}
44 50
45impl PreviewManager { 51impl PreviewManager {
@@ -51,17 +57,17 @@ impl PreviewManager {
51 } 57 }
52 } 58 }
53 59
54 pub fn get(&self, source: &MediaSource) -> Option<&ImageStatus> { 60 pub fn get(&self, source: &MediaSource, kind: PreviewKind) -> Option<&ImageStatus> {
55 self.previews.get(&source.unique_key()) 61 self.previews.get(&(source.unique_key(), kind))
56 } 62 }
57 63
58 fn insert(&mut self, key: String, status: ImageStatus) { 64 fn insert(&mut self, key: String, kind: PreviewKind, status: ImageStatus) {
59 self.previews.insert(key, status); 65 self.previews.insert((key, kind), status);
60 } 66 }
61 67
62 /// Queue download and preparation of preview 68 /// Queue download and preparation of preview
63 pub fn load(&mut self, source: &MediaSource, worker: &Requester) { 69 pub fn load(&mut self, source: &MediaSource, kind: PreviewKind, worker: &Requester) {
64 let Some(status) = self.previews.get_mut(&source.unique_key()) else { 70 let Some(status) = self.previews.get_mut(&(source.unique_key(), kind)) else {
65 return; 71 return;
66 }; 72 };
67 let Some(picker) = &self.picker else { return }; 73 let Some(picker) = &self.picker else { return };
@@ -72,6 +78,7 @@ impl PreviewManager {
72 78
73 worker.load_image( 79 worker.load_image(
74 source.to_owned(), 80 source.to_owned(),
81 kind,
75 size.to_owned(), 82 size.to_owned(),
76 Arc::clone(picker), 83 Arc::clone(picker),
77 Arc::clone(&self.permits), 84 Arc::clone(&self.permits),
@@ -83,6 +90,7 @@ impl PreviewManager {
83 &mut self, 90 &mut self,
84 settings: &ApplicationSettings, 91 settings: &ApplicationSettings,
85 source: MediaSource, 92 source: MediaSource,
93 kind: PreviewKind,
86 size: ImagePreviewSize, 94 size: ImagePreviewSize,
87 worker: &Requester, 95 worker: &Requester,
88 ) { 96 ) {
@@ -90,7 +98,7 @@ impl PreviewManager {
90 return; 98 return;
91 } 99 }
92 100
93 let key = source.unique_key(); 101 let key = (source.unique_key(), kind);
94 if self.previews.contains_key(&key) { 102 if self.previews.contains_key(&key) {
95 return; 103 return;
96 } 104 }
@@ -102,7 +110,7 @@ impl PreviewManager {
102 .as_ref() 110 .as_ref()
103 .is_some_and(|setting| !setting.lazy_load) 111 .is_some_and(|setting| !setting.lazy_load)
104 { 112 {
105 self.load(&source, worker); 113 self.load(&source, kind, worker);
106 } 114 }
107 } 115 }
108} 116}
@@ -133,6 +141,7 @@ pub async fn load_image(
133 store: AsyncProgramStore, 141 store: AsyncProgramStore,
134 media: Media, 142 media: Media,
135 source: MediaSource, 143 source: MediaSource,
144 kind: PreviewKind,
136 picker: Arc<Picker>, 145 picker: Arc<Picker>,
137 permits: Arc<Semaphore>, 146 permits: Arc<Semaphore>,
138 size: ImagePreviewSize, 147 size: ImagePreviewSize,
@@ -178,5 +187,5 @@ pub async fn load_image(
178 }; 187 };
179 188
180 let mut locked = store.lock().await; 189 let mut locked = store.lock().await;
181 locked.application.previews.insert(key, status); 190 locked.application.previews.insert(key, kind, status);
182} 191}
src/tests.rs +1
@@ -208,6 +208,7 @@ pub fn mock_tunables() -> TunableValues {
208 members_split: Default::default(), 208 members_split: Default::default(),
209 default_split: Default::default(), 209 default_split: Default::default(),
210 ssl_verify: true, 210 ssl_verify: true,
211 cache_policy: Default::default(),
211 } 212 }
212} 213}
213 214
src/windows/room/chat.rs +13 −12
@@ -542,21 +542,22 @@ impl ChatState {
542 None => return Ok(None), 542 None => return Ok(None),
543 }; 543 };
544 544
545 let reactions = reactions.iter().filter_map(|(event_id, (reaction, user_id))| { 545 let reactions =
546 if user_id != &settings.profile.user_id { 546 reactions.iter().filter_map(|(event_id, (reaction, user_id, _))| {
547 return None; 547 if user_id != &settings.profile.user_id {
548 } 548 return None;
549 }
549 550
550 if let Some(emoji) = &emoji { 551 if let Some(emoji) = &emoji {
551 if emoji == reaction { 552 if emoji == reaction {
552 return Some(event_id); 553 return Some(event_id);
554 } else {
555 return None;
556 }
553 } else { 557 } else {
554 return None; 558 return Some(event_id);
555 } 559 }
556 } else { 560 });
557 return Some(event_id);
558 }
559 });
560 561
561 for reaction in reactions { 562 for reaction in reactions {
562 let _ = room.redact(reaction, None, None).await.map_err(IambError::from)?; 563 let _ = room.redact(reaction, None, None).await.map_err(IambError::from)?;
src/windows/room/scrollback.rs +28 −25
@@ -55,7 +55,7 @@ use crate::{
55 }, 55 },
56 config::ApplicationSettings, 56 config::ApplicationSettings,
57 message::{Message, MessageCursor, MessageKey, Messages}, 57 message::{Message, MessageCursor, MessageKey, Messages},
58 preview::PreviewManager, 58 preview::{PreviewKind, PreviewManager},
59}; 59};
60 60
61fn no_msgs() -> EditError<IambInfo> { 61fn no_msgs() -> EditError<IambInfo> {
@@ -1364,12 +1364,13 @@ 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 (_, item) in thread.range(&corner_key..).rev() { 1367 for (key, item) in thread.range(&corner_key..).rev() {
1368 if let Some(source) = &item.image_preview { 1368 if let Some(source) = &item.image_preview {
1369 self.store 1369 self.store.application.previews.load(
1370 .application 1370 source,
1371 .previews 1371 PreviewKind::Message,
1372 .load(source, &self.store.application.worker); 1372 &self.store.application.worker,
1373 );
1373 } 1374 }
1374 let reply = item 1375 let reply = item
1375 .reply_to() 1376 .reply_to()
@@ -1377,10 +1378,20 @@ impl StatefulWidget for Scrollback<'_> {
1377 .and_then(|e| info.get_event(&e)) 1378 .and_then(|e| info.get_event(&e))
1378 .and_then(|msg| msg.image_preview.as_ref()); 1379 .and_then(|msg| msg.image_preview.as_ref());
1379 if let Some(source) = reply { 1380 if let Some(source) = reply {
1380 self.store 1381 self.store.application.previews.load(
1381 .application 1382 source,
1382 .previews 1383 PreviewKind::Message,
1383 .load(source, &self.store.application.worker); 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 }
1384 } 1395 }
1385 } 1396 }
1386 1397
@@ -1388,7 +1399,7 @@ impl StatefulWidget for Scrollback<'_> {
1388 for (key, item) in thread.range(&corner_key..) { 1399 for (key, item) in thread.range(&corner_key..) {
1389 let sel = key == cursor_key; 1400 let sel = key == cursor_key;
1390 1401
1391 let (txt, [mut msg_preview, mut reply_preview]) = 1402 let (txt, mut msg_previews) =
1392 item.show_with_preview(prev, foc && sel, &state.viewctx, info, settings, previews); 1403 item.show_with_preview(prev, foc && sel, &state.viewctx, info, settings, previews);
1393 1404
1394 let incomplete_ok = !full || !sel; 1405 let incomplete_ok = !full || !sel;
@@ -1405,17 +1416,9 @@ impl StatefulWidget for Scrollback<'_> {
1405 continue; 1416 continue;
1406 } 1417 }
1407 1418
1408 // Only take the preview into the matching row number. 1419 // Only take the previews into the matching row number.
1409 // `reply` and `msg` previews are on rows, 1420 let line_preview: Vec<_> =
1410 // so an `or` works to pick the one that matches (if any) 1421 msg_previews.extract_if(.., |(_, _, y)| *y as usize == row).collect();
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 1422
1420 lines.push((key, row, line, line_preview)); 1423 lines.push((key, row, line, line_preview));
1421 sawit |= sel; 1424 sawit |= sel;
@@ -1440,9 +1443,9 @@ impl StatefulWidget for Scrollback<'_> {
1440 let mut image_previews = vec![]; 1443 let mut image_previews = vec![];
1441 for (_, _, txt, line_preview) in lines.into_iter() { 1444 for (_, _, txt, line_preview) in lines.into_iter() {
1442 let _ = buf.set_line(x, y, &txt, area.width); 1445 let _ = buf.set_line(x, y, &txt, area.width);
1443 if let Some((backend, msg_x, _)) = line_preview { 1446 image_previews.extend(
1444 image_previews.push((x + msg_x, y, backend)); 1447 line_preview.into_iter().map(|(backend, msg_x, _)| (x + msg_x, y, backend)),
1445 } 1448 );
1446 1449
1447 y += 1; 1450 y += 1;
1448 } 1451 }
src/worker.rs +33 −10
@@ -98,7 +98,7 @@ use crate::base::{EchoLocation, MessageNeed};
98use crate::config::{ImagePreviewSize, ProxyUrl}; 98use crate::config::{ImagePreviewSize, ProxyUrl};
99use crate::message::{Message, MessageEvent, MessageId, MessageKey}; 99use crate::message::{Message, MessageEvent, MessageId, MessageKey};
100use crate::notifications::register_notifications; 100use crate::notifications::register_notifications;
101use crate::preview::load_image; 101use crate::preview::PreviewKind;
102use crate::{ 102use crate::{
103 ApplicationSettings, 103 ApplicationSettings,
104 base::{ 104 base::{
@@ -326,7 +326,7 @@ fn load_insert(
326 info.insert_with_preview(msg, settings, previews, worker); 326 info.insert_with_preview(msg, settings, previews, worker);
327 }, 327 },
328 AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Reaction(ev)) => { 328 AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Reaction(ev)) => {
329 info.insert_reaction(ev); 329 info.insert_reaction_with_preview(ev, settings, previews, worker);
330 }, 330 },
331 AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Sticker(ev)) => { 331 AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Sticker(ev)) => {
332 info.insert_sticker(ev, settings, previews, worker); 332 info.insert_sticker(ev, settings, previews, worker);
@@ -726,7 +726,7 @@ pub enum WorkerTask {
726 TypingNotice(OwnedRoomId), 726 TypingNotice(OwnedRoomId),
727 Verify(VerifyAction, SasVerification, ClientReply<IambResult<EditInfo>>), 727 Verify(VerifyAction, SasVerification, ClientReply<IambResult<EditInfo>>),
728 VerifyRequest(OwnedUserId, ClientReply<IambResult<EditInfo>>), 728 VerifyRequest(OwnedUserId, ClientReply<IambResult<EditInfo>>),
729 LoadImage(MediaSource, ImagePreviewSize, Arc<Picker>, Arc<Semaphore>), 729 LoadImage(MediaSource, PreviewKind, ImagePreviewSize, Arc<Picker>, Arc<Semaphore>),
730} 730}
731 731
732impl Debug for WorkerTask { 732impl Debug for WorkerTask {
@@ -790,9 +790,10 @@ impl Debug for WorkerTask {
790 .field(&format_args!("_")) 790 .field(&format_args!("_"))
791 .finish() 791 .finish()
792 }, 792 },
793 WorkerTask::LoadImage(source, size, _, _) => { 793 WorkerTask::LoadImage(source, kind, size, _, _) => {
794 f.debug_tuple("WorkerTask::RenderImage") 794 f.debug_tuple("WorkerTask::RenderImage")
795 .field(source) 795 .field(source)
796 .field(kind)
796 .field(size) 797 .field(size)
797 .field(&format_args!("_")) 798 .field(&format_args!("_"))
798 .field(&format_args!("_")) 799 .field(&format_args!("_"))
@@ -845,7 +846,10 @@ async fn create_client_inner(
845 846
846 let http = builder.build().map_err(matrix_sdk::HttpError::Reqwest)?; 847 let http = builder.build().map_err(matrix_sdk::HttpError::Reqwest)?;
847 848
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);
849 853
850 // Set up the Matrix client for the selected profile. 854 // Set up the Matrix client for the selected profile.
851 let builder = Client::builder() 855 let builder = Client::builder()
@@ -881,6 +885,12 @@ pub async fn create_client(settings: &ApplicationSettings) -> Client {
881 885
882 client.event_cache().subscribe().expect("Failed to start event cache"); 886 client.event_cache().subscribe().expect("Failed to start event cache");
883 887
888 client
889 .media()
890 .set_media_retention_policy(settings.tunables.cache_policy)
891 .await
892 .expect("Failed to start event cache");
893
884 client 894 client
885} 895}
886 896
@@ -978,11 +988,14 @@ impl Requester {
978 pub fn load_image( 988 pub fn load_image(
979 &self, 989 &self,
980 source: MediaSource, 990 source: MediaSource,
991 kind: PreviewKind,
981 size: ImagePreviewSize, 992 size: ImagePreviewSize,
982 picker: Arc<Picker>, 993 picker: Arc<Picker>,
983 permits: Arc<Semaphore>, 994 permits: Arc<Semaphore>,
984 ) { 995 ) {
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();
986 } 999 }
987} 1000}
988 1001
@@ -1081,12 +1094,13 @@ impl ClientWorker {
1081 assert!(self.initialized); 1094 assert!(self.initialized);
1082 reply.send(self.verify_request(user_id).await); 1095 reply.send(self.verify_request(user_id).await);
1083 }, 1096 },
1084 WorkerTask::LoadImage(source, size, picker, permits) => { 1097 WorkerTask::LoadImage(source, kind, size, picker, permits) => {
1085 assert!(self.initialized); 1098 assert!(self.initialized);
1086 tokio::spawn(load_image( 1099 tokio::spawn(crate::preview::load_image(
1087 self.store.clone().unwrap(), 1100 self.store.clone().unwrap(),
1088 self.client.media(), 1101 self.client.media(),
1089 source, 1102 source,
1103 kind,
1090 picker, 1104 picker,
1091 permits, 1105 permits,
1092 size, 1106 size,
@@ -1188,9 +1202,18 @@ impl ClientWorker {
1188 let sender = ev.sender().to_owned(); 1202 let sender = ev.sender().to_owned();
1189 let _ = locked.application.presences.get_or_default(sender); 1203 let _ = locked.application.presences.get_or_default(sender);
1190 1204
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
1192 update_event_receipts(info, &room, ev.event_id()).await; 1209 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 );
1194 } 1217 }
1195 }, 1218 },
1196 ); 1219 );