Commit a97c3c9f3c

a97c3c9f3cb84ed263027c663af42c8326ed8bb3

parent: 711297d5ba

Unregistered key

vaw <git@nlih.de> · 2026-11-17 05:48 UTC
committer: <noreply@github.com>

Render `img` tags in formatted HTML bodies (#848)

Layout: unified · split

src/base.rs +51 −47
@@ -1768,6 +1768,24 @@ impl RoomInfo {
17681768 self.set_implicit_receipt(sender, event_id);
17691769 }
17701770
1771 /// Insert a message with a [`EventLocation::Message`] and previews.
1772 fn insert_msglike_with_preview(
1773 &mut self,
1774 event_id: OwnedEventId,
1775 thread_root: Option<OwnedEventId>,
1776 message: Message,
1777 settings: &ApplicationSettings,
1778 previews: &mut PreviewManager,
1779 ) {
1780 if settings.tunables.image_preview.enabled {
1781 for (source, kind) in message.image_previews() {
1782 previews.register_preview(settings, source, kind);
1783 }
1784 }
1785
1786 self.insert_msglike(event_id, thread_root, message);
1787 }
1788
17711789 /// Insert a reaction to a message.
17721790 fn insert_reaction(&mut self, react: ReactionEvent, source: Option<MediaSource>) {
17731791 let MessageLikeEvent::Original(react) = react else {
@@ -1787,7 +1805,7 @@ impl RoomInfo {
17871805 }
17881806
17891807 /// Insert a sticker
1790 pub fn insert_sticker_with_preview(
1808 pub fn insert_sticker(
17911809 &mut self,
17921810 sticker: StickerEvent,
17931811 settings: &ApplicationSettings,
@@ -1806,17 +1824,7 @@ impl RoomInfo {
18061824 _ => None,
18071825 };
18081826
1809 if let MessageLikeEvent::Original(OriginalMessageLikeEvent {
1810 content: StickerEventContent { source, .. },
1811 ..
1812 }) = &sticker &&
1813 settings.tunables.image_preview.enabled
1814 {
1815 let source = source.clone().into();
1816 previews.register_preview(settings, &source, PreviewKind::Message);
1817 }
1818
1819 self.insert_msglike(event_id, thread_root, sticker.into());
1827 self.insert_msglike_with_preview(event_id, thread_root, sticker.into(), settings, previews);
18201828 }
18211829
18221830 /// Insert a reaction to a message.
@@ -1839,7 +1847,7 @@ impl RoomInfo {
18391847 if settings.tunables.image_preview.enabled &&
18401848 let Some(source) = source.as_ref()
18411849 {
1842 previews.register_preview(settings, source, PreviewKind::Reaction);
1850 previews.register_preview(settings, source, PreviewKind::Emoji);
18431851 }
18441852
18451853 self.insert_reaction(react, source);
@@ -2028,6 +2036,8 @@ impl RoomInfo {
20282036 &mut self,
20292037 edit_msg: RoomMessageEvent,
20302038 replacement: Replacement<RoomMessageEventContentWithoutRelation>,
2039 settings: &ApplicationSettings,
2040 previews: &mut PreviewManager,
20312041 ) {
20322042 let RoomMessageEvent::Original(edit_msg) = edit_msg else {
20332043 return;
@@ -2044,6 +2054,12 @@ impl RoomInfo {
20442054 return;
20452055 };
20462056 msg.insert_edit(edit_key.clone(), replacement.new_content);
2057
2058 if settings.tunables.image_preview.enabled {
2059 for (source, kind) in msg.image_previews() {
2060 previews.register_preview(settings, source, kind);
2061 }
2062 }
20472063 } else {
20482064 // The edited message is not yet loaded
20492065 let entry = self.unloaded_edits.entry(replacement.event_id.clone());
@@ -2075,44 +2091,28 @@ impl RoomInfo {
20752091 self.insert_msglike(event_id, thread_root, msg.into());
20762092 }
20772093
2078 /// Insert a new message.
2079 fn insert_message(&mut self, msg: RoomMessageEvent) {
2080 let event_id = msg.event_id().to_owned();
2081 let thread_root = match msg.as_original().and_then(|ev| ev.content.relates_to.as_ref()) {
2094 /// Insert a new message event, and prepare for image-preview if it has an image attachment.
2095 pub fn insert_message(
2096 &mut self,
2097 ev: RoomMessageEvent,
2098 settings: &ApplicationSettings,
2099 previews: &mut PreviewManager,
2100 ) {
2101 let event_id = ev.event_id().to_owned();
2102 let thread_root = match ev.as_original().and_then(|ev| ev.content.relates_to.as_ref()) {
20822103 Some(Relation::Replacement(repl)) => {
20832104 let repl = repl.to_owned();
2084 self.insert_edit(msg, repl);
2105 self.insert_edit(ev, repl, settings, previews);
20852106 return;
20862107 },
20872108 Some(Relation::Thread(Thread { event_id, .. })) => Some(event_id.to_owned()),
20882109 _ => None,
20892110 };
2090
2091 let mut message: Message = msg.into();
2111 let mut message: Message = ev.into();
20922112 if let Some(edits) = self.unloaded_edits.remove(&event_id) {
20932113 message.set_edits(edits);
20942114 }
2095
2096 self.insert_msglike(event_id, thread_root, message);
2097 }
2098
2099 /// Insert a new message event, and prepare for image-preview if it has an image attachment.
2100 pub fn insert_with_preview(
2101 &mut self,
2102 ev: RoomMessageEvent,
2103 settings: &ApplicationSettings,
2104 previews: &mut PreviewManager,
2105 ) {
2106 if let MessageLikeEvent::Original(OriginalMessageLikeEvent {
2107 content: RoomMessageEventContent { msgtype: MessageType::Image(c), .. },
2108 ..
2109 }) = &ev &&
2110 settings.tunables.image_preview.enabled
2111 {
2112 previews.register_preview(settings, &c.source, PreviewKind::Message)
2113 }
2114
2115 self.insert_message(ev);
2115 self.insert_msglike_with_preview(event_id, thread_root, message, settings, previews);
21162116 }
21172117
21182118 /// Indicates whether this room has unread messages.
@@ -3234,7 +3234,7 @@ pub mod tests {
32343234 MSG5_KEY.clone(),
32353235 );
32363236
3237 info.insert_with_preview(event, &settings, &mut previews);
3237 info.insert_message(event, &settings, &mut previews);
32383238
32393239 assert_eq!(
32403240 info.user_receipts
@@ -3266,8 +3266,8 @@ pub mod tests {
32663266 MSG2_KEY.clone(),
32673267 );
32683268
3269 info.insert_with_preview(newer, &settings, &mut previews);
3270 info.insert_with_preview(older, &settings, &mut previews);
3269 info.insert_message(newer, &settings, &mut previews);
3270 info.insert_message(older, &settings, &mut previews);
32713271
32723272 assert_eq!(
32733273 info.user_receipts
@@ -3314,6 +3314,8 @@ pub mod tests {
33143314
33153315 #[test]
33163316 fn test_explicit_receipt_does_not_move_implicit_receipt_backwards() {
3317 let settings = mock_settings();
3318 let mut previews = PreviewManager::new(&settings);
33173319 let mut info = RoomInfo::default();
33183320 let older = mock_room_message_event(
33193321 RoomMessageEventContent::text_plain("older"),
@@ -3326,8 +3328,8 @@ pub mod tests {
33263328 MSG5_KEY.clone(),
33273329 );
33283330
3329 info.insert_message(older);
3330 info.insert_message(newer);
3331 info.insert_message(older, &settings, &mut previews);
3332 info.insert_message(newer, &settings, &mut previews);
33313333 info.set_receipt(ReceiptThread::Main, TEST_USER2.clone(), MSG2_EVID.clone());
33323334
33333335 assert_eq!(
@@ -3340,6 +3342,8 @@ pub mod tests {
33403342
33413343 #[test]
33423344 fn test_implicit_receipt_waits_for_unloaded_explicit_receipt() {
3345 let settings = mock_settings();
3346 let mut previews = PreviewManager::new(&settings);
33433347 let mut info = RoomInfo::default();
33443348 info.set_receipt(ReceiptThread::Main, TEST_USER2.clone(), MSG5_EVID.clone());
33453349 let older = mock_room_message_event(
@@ -3348,7 +3352,7 @@ pub mod tests {
33483352 MSG2_KEY.clone(),
33493353 );
33503354
3351 info.insert_message(older);
3355 info.insert_message(older, &settings, &mut previews);
33523356
33533357 assert_eq!(
33543358 info.user_receipts
src/message/html.rs +235 −36
@@ -18,10 +18,14 @@ use html5ever::tendril::{StrTendril, TendrilSink};
1818use html5ever::{local_name, ns};
1919use markup5ever_rcdom::{Handle, NodeData, RcDom};
2020use matrix_sdk::OwnedServerName;
21use matrix_sdk::ruma::OwnedMxcUri;
22use matrix_sdk::ruma::events::room::ImageInfo;
2123
2224use crate::message::printer::TextPrinter;
25use crate::message::{ProtocolPreview, placeholder_frame};
2326use crate::prelude::*;
24use crate::util::{join_cell_text, space_text};
27use crate::preview::ImageStatus;
28use crate::util::{join_cell_text, space_text, wrapped_text};
2529
2630/// Generate bullet points from a [ListStyle].
2731pub struct BulletIterator {
@@ -101,6 +105,12 @@ impl TableRow {
101105 }
102106 }
103107
108 pub fn image_previews<'a>(&'a self, previews: &mut Vec<(&'a MediaSource, PreviewKind)>) {
109 for (_, cell) in &self.cells {
110 cell.image_previews(previews);
111 }
112 }
113
104114 fn columns(&self) -> usize {
105115 self.cells.len()
106116 }
@@ -119,6 +129,12 @@ impl TableSection {
119129 }
120130 }
121131
132 pub fn image_previews<'a>(&'a self, previews: &mut Vec<(&'a MediaSource, PreviewKind)>) {
133 for row in &self.rows {
134 row.image_previews(previews);
135 }
136 }
137
122138 fn columns(&self) -> usize {
123139 self.rows.iter().map(TableRow::columns).max().unwrap_or(0)
124140 }
@@ -142,16 +158,16 @@ impl Table {
142158 }
143159 }
144160
145 fn to_text<'a>(
146 &'a self,
147 width: usize,
148 style: Style,
149 settings: &'a ApplicationSettings,
150 info: &'a RoomInfo,
151 ) -> Text<'a> {
161 pub fn image_previews<'a>(&'a self, previews: &mut Vec<(&'a MediaSource, PreviewKind)>) {
162 for section in &self.sections {
163 section.image_previews(previews);
164 }
165 }
166
167 fn to_text<'a>(&'a self, printer: &TextPrinter<'a>, style: Style) -> Text<'a> {
152168 let mut text = Text::default();
153169 let columns = self.columns();
154 let cell_total = width.saturating_sub(columns).saturating_sub(1);
170 let cell_total = printer.width().saturating_sub(columns).saturating_sub(1);
155171 let cell_min = cell_total.checked_div(columns).unwrap_or(0);
156172 let mut cell_slop = cell_total - cell_min * columns;
157173 let cell_widths = (0..columns)
@@ -164,16 +180,14 @@ impl Table {
164180
165181 let mut nrows = 0;
166182
167 let line_style = style.patch(settings.theme.messages.table);
168 let line = settings.theme.messages.table_line.to_table_set();
183 let line_style = style.patch(printer.settings.theme.messages.table);
184 let line = printer.settings.theme.messages.table_line.to_table_set();
169185
170186 if let Some(caption) = &self.caption {
171 let subw = width.saturating_sub(6);
172 let mut printer =
173 TextPrinter::new(subw, style, settings, info).align(Alignment::Center);
187 let mut printer = printer.sub(6).align(Alignment::Center);
174188 caption.print(&mut printer, style);
175189
176 for mut line in printer.finish().lines {
190 for mut line in printer.finish().0.lines {
177191 line.spans.insert(0, Span::styled(" ", style));
178192 line.spans.push(Span::styled(" ", style));
179193 text.lines.push(line);
@@ -222,7 +236,7 @@ impl Table {
222236 CellType::Data => style,
223237 };
224238
225 cell.to_text(*w, style, settings, info)
239 cell.to_text(*w, style, printer.settings, printer.info)
226240 } else {
227241 space_text(*w, style)
228242 };
@@ -282,6 +296,49 @@ impl ThemeSelector {
282296 }
283297}
284298
299#[derive(Debug, Clone)]
300pub struct Image {
301 title: Option<String>,
302 alt: Option<String>,
303 width: Option<u16>,
304 height: Option<u16>,
305 src: Option<MediaSource>,
306 is_emote: bool,
307}
308
309impl Image {
310 pub fn new(src: MediaSource, info: Option<&ImageInfo>) -> Self {
311 let width = info
312 .and_then(|info| info.width)
313 .and_then(|width| u16::try_from(width).ok());
314 let height = info
315 .and_then(|info| info.height)
316 .and_then(|height| u16::try_from(height).ok());
317
318 Self {
319 src: Some(src),
320 width,
321 height,
322
323 title: None,
324 alt: None,
325 is_emote: false,
326 }
327 }
328
329 fn kind(&self) -> PreviewKind {
330 if self.is_emote {
331 return PreviewKind::Emoji;
332 }
333
334 PreviewKind::Custom(self.width, self.height)
335 }
336
337 fn preview<'a>(&self, previews: &'a PreviewManager) -> Option<&'a ImageStatus> {
338 self.src.as_ref().and_then(|src| previews.get(src, self.kind()))
339 }
340}
341
285342/// A processed HTML element that we can render to the terminal.
286343#[derive(Debug, Clone)]
287344pub enum StyleTreeNode {
@@ -291,7 +348,7 @@ pub enum StyleTreeNode {
291348 #[allow(dead_code)]
292349 Code(Box<StyleTreeNode>, Option<String>),
293350 Header(Box<StyleTreeNode>, usize),
294 Image(Option<String>),
351 Image(Image),
295352 List(StyleTreeChildren, ListStyle),
296353 Paragraph(Box<StyleTreeNode>),
297354 Pre(Box<StyleTreeNode>),
@@ -315,9 +372,9 @@ impl StyleTreeNode {
315372 settings: &'a ApplicationSettings,
316373 info: &'a RoomInfo,
317374 ) -> Text<'a> {
318 let mut printer = TextPrinter::new(width, style, settings, info);
375 let mut printer = TextPrinter::new(width, style, settings, info, None);
319376 self.print(&mut printer, style);
320 printer.finish()
377 printer.finish().0
321378 }
322379
323380 pub fn gather_links(&self, urls: &mut Vec<(char, Url)>) {
@@ -379,13 +436,52 @@ impl StyleTreeNode {
379436 }
380437 },
381438
382 StyleTreeNode::Image(_) => {},
439 StyleTreeNode::Image(..) => {},
383440 StyleTreeNode::Ruler => {},
384441 StyleTreeNode::Text(_) => {},
385442 StyleTreeNode::Break => {},
386443 }
387444 }
388445
446 pub fn image_previews<'a>(&'a self, previews: &mut Vec<(&'a MediaSource, PreviewKind)>) {
447 match self {
448 StyleTreeNode::Image(img) => {
449 if let Some(source) = &img.src {
450 previews.push((source, img.kind()));
451 }
452 },
453
454 StyleTreeNode::Blockquote(child) |
455 StyleTreeNode::Code(child, _) |
456 StyleTreeNode::Header(child, _) |
457 StyleTreeNode::Paragraph(child) |
458 StyleTreeNode::Pre(child) |
459 StyleTreeNode::Style(child, _) |
460 StyleTreeNode::Themed(child, _) => {
461 child.image_previews(previews);
462 },
463
464 StyleTreeNode::List(children, _) | StyleTreeNode::Sequence(children) => {
465 for child in children {
466 child.image_previews(previews);
467 }
468 },
469
470 StyleTreeNode::Table(table) => {
471 table.image_previews(previews);
472 },
473
474 StyleTreeNode::Ruler |
475 StyleTreeNode::Text(..) |
476 StyleTreeNode::Break |
477 StyleTreeNode::Anchor(..) |
478 StyleTreeNode::RoomAlias(..) |
479 StyleTreeNode::RoomId(..) |
480 StyleTreeNode::UserId(..) |
481 StyleTreeNode::DisplayName(..) => {},
482 }
483 }
484
389485 pub fn print<'a>(&'a self, printer: &mut TextPrinter<'a>, style: Style) {
390486 let width = printer.width();
391487
@@ -406,7 +502,7 @@ impl StyleTreeNode {
406502 let mut subp = printer.sub(3);
407503 child.print(&mut subp, style);
408504
409 for mut line in subp.finish() {
505 for mut line in subp.finish().0 {
410506 line.spans.insert(0, Span::styled(" ", style));
411507 line.spans.insert(0, Span::styled(quote, quote_style));
412508 line.spans.insert(0, Span::styled(" ", style));
@@ -432,11 +528,48 @@ impl StyleTreeNode {
432528 printer.push_str(" ", style);
433529 child.print(printer, style);
434530 },
435 StyleTreeNode::Image(None) => {},
436 StyleTreeNode::Image(Some(alt)) => {
531 StyleTreeNode::Image(img @ Image { is_emote: true, .. }) => {
532 if let Some(previews) = printer.previews &&
533 let Some(image) = img.preview(previews) &&
534 let ImageStatus::Loaded(image) = image
535 {
536 printer.push_emoji(image, style);
537 } else {
538 let title = img.title.as_deref().unwrap_or("emote");
539 printer.push_span_nobreak(Span::styled(format!(":{title}:"), style));
540 }
541 },
542 StyleTreeNode::Image(img) => {
543 let alt = img.alt.as_deref().or(img.title.as_deref());
544
545 let mut proto = None;
546 let placeholder = match printer.previews.and_then(|previews| img.preview(previews))
547 {
548 None => {
549 if let Some(alt) = alt {
550 format!("[Image Alt: {alt}]")
551 } else {
552 "[Image]".to_string()
553 }
554 },
555 Some(ImageStatus::Queued(image_preview_size)) => {
556 placeholder_frame(Some("Queued..."), width, image_preview_size)
557 },
558 Some(ImageStatus::Downloading(image_preview_size)) => {
559 placeholder_frame(Some("Downloading..."), width, image_preview_size)
560 },
561 Some(ImageStatus::Loaded(backend)) => {
562 proto = Some(backend);
563 placeholder_frame(None, width, &backend.size())
564 },
565 Some(ImageStatus::Error(err)) => format!("[Image error: {err}]\n"),
566 };
567
437568 printer.commit();
438 printer.push_str("Image Alt: ", style);
439 printer.push_str(alt, style);
569 if let Some(proto) = proto {
570 printer.push_image(proto);
571 }
572 printer.push_text(wrapped_text(placeholder, width, style));
440573 printer.commit();
441574 },
442575 StyleTreeNode::List(children, lt) => {
@@ -448,7 +581,7 @@ impl StyleTreeNode {
448581 let mut bullet = bullets.next();
449582 child.print(&mut subp, style);
450583
451 for mut line in subp.finish() {
584 for mut line in subp.finish().0 {
452585 let leading = if let Some(bullet) = bullet.take() {
453586 Span::styled(bullet, style)
454587 } else {
@@ -484,7 +617,7 @@ impl StyleTreeNode {
484617 .into(),
485618 );
486619
487 for mut line in subp.finish() {
620 for mut line in subp.finish().0 {
488621 line.spans.insert(0, Span::styled(border.vertical_left, style));
489622 line.spans.push(Span::styled(border.vertical_right, style));
490623 printer.push_line(line);
@@ -510,7 +643,7 @@ impl StyleTreeNode {
510643 }
511644 },
512645 StyleTreeNode::Table(table) => {
513 let text = table.to_text(width, style, printer.settings, printer.info);
646 let text = table.to_text(printer, style);
514647 printer.push_text(text);
515648 },
516649 StyleTreeNode::Break => {
@@ -597,6 +730,16 @@ impl StyleTree {
597730 return links;
598731 }
599732
733 pub fn image_previews(&self) -> Vec<(&MediaSource, PreviewKind)> {
734 let mut previews = vec![];
735
736 for child in &self.children {
737 child.image_previews(&mut previews);
738 }
739
740 return previews;
741 }
742
600743 pub fn to_text<'a>(
601744 &'a self,
602745 width: usize,
@@ -604,7 +747,25 @@ impl StyleTree {
604747 settings: &'a ApplicationSettings,
605748 info: &'a RoomInfo,
606749 ) -> Text<'a> {
607 let mut printer = TextPrinter::new(width, style, settings, info);
750 let mut printer = TextPrinter::new(width, style, settings, info, None);
751
752 for child in self.children.iter() {
753 child.print(&mut printer, style);
754 }
755
756 printer.finish().0
757 }
758
759 /// The images are in the format `(protocol, x, y)`
760 pub fn render<'a>(
761 &'a self,
762 width: usize,
763 style: Style,
764 settings: &'a ApplicationSettings,
765 info: &'a RoomInfo,
766 previews: &'a PreviewManager,
767 ) -> (Text<'a>, Vec<ProtocolPreview>) {
768 let mut printer = TextPrinter::new(width, style, settings, info, Some(previews));
608769
609770 for child in self.children.iter() {
610771 child.print(&mut printer, style);
@@ -737,16 +898,54 @@ fn attrs_to_start(attrs: &[Attribute]) -> Option<usize> {
737898 return None;
738899}
739900
740fn attrs_to_alt(attrs: &[Attribute]) -> Option<String> {
901fn attrs_to_image(attrs: &[Attribute]) -> Image {
902 let mut title = None;
903 let mut alt = None;
904 let mut width = None;
905 let mut height = None;
906 let mut src = None;
907 let mut is_emote = false;
908
741909 for attr in attrs {
742 if attr.name.local.as_ref() != "alt" {
743 continue;
744 }
910 match attr.name.local.as_ref() {
911 "title" => {
912 title = Some(attr.value.to_string());
913 },
914 "alt" => {
915 alt = Some(attr.value.to_string());
916 },
917 "width" => {
918 if let Ok(val) = u16::from_str(attr.value.as_ref()) {
919 width = Some(val);
920 }
921 },
922 "height" => {
923 if let Ok(val) = u16::from_str(attr.value.as_ref()) {
924 height = Some(val);
925 }
926 },
927 "src" => {
928 let uri = OwnedMxcUri::from(attr.value.to_string());
745929
746 return Some(attr.value.to_string());
930 if uri.is_valid() {
931 src = Some(uri);
932 }
933 },
934 "data-mx-emoticon" => {
935 is_emote = true;
936 },
937 _ => (),
938 }
747939 }
748940
749 return None;
941 Image {
942 title,
943 alt,
944 width,
945 height,
946 is_emote,
947 src: src.map(MediaSource::Plain),
948 }
750949}
751950
752951fn attrs_to_href(attrs: &[Attribute]) -> Option<String> {
@@ -945,7 +1144,7 @@ fn h2t(hdl: &Handle, state: &mut TreeGenState) -> StyleTreeChildren {
9451144 "hr" => StyleTreeNode::Ruler,
9461145 "br" => StyleTreeNode::Break,
9471146
948 "img" => StyleTreeNode::Image(attrs_to_alt(&attrs.borrow())),
1147 "img" => StyleTreeNode::Image(attrs_to_image(&attrs.borrow())),
9491148
9501149 // These don't render in any special way.
9511150 "details" | "html" | "summary" | "sub" | "sup" => {
src/message/mod.rs +166 −160
@@ -33,7 +33,6 @@ use matrix_sdk::ruma::{OwnedTransactionId, UserId};
3333use matrix_sdk::send_queue::SendHandle;
3434use modalkit::editing::cursor::Cursor;
3535use ratatui::symbols::line::{HORIZONTAL, THICK_VERTICAL};
36use ratatui_image::sliced::SlicedProtocol;
3736
3837use crate::base::MessageEdits;
3938use crate::message::html::{StyleTree, parse_matrix_html};
@@ -53,6 +52,7 @@ pub mod poll;
5352pub use self::compose::{text_to_message, text_to_text_message_event_content};
5453pub use self::html::TreeGenState;
5554
55/// `proto, x, y`
5656type ProtocolPreview = (Arc<SlicedProtocol>, u16, u16);
5757
5858/// The key used for uniquely identifying messages within a room and its threads.
@@ -114,6 +114,51 @@ const MIN_MSG_LEN: usize = 30;
114114
115115const USIZE_TOO_SMALL: bool = usize::BITS < u64::BITS;
116116
117/// Macro rule converting a File / Image / Audio / Video to its text content with the shape:
118/// `[Attached <type>: <content>[ (<human readable file size>)]]`
119macro_rules! display_file_name {
120 ( $msgtype:ident, $content:expr ) => {{
121 format!(
122 "[Attached {}: {}{}]",
123 stringify!($msgtype),
124 $content.filename(),
125 $content
126 .info
127 .as_ref()
128 .map(|info| {
129 info.size
130 .map(|s| format!(" ({})", format_size(u64::from(s), DECIMAL)))
131 .unwrap_or_else(String::new)
132 })
133 .unwrap_or_else(String::new)
134 )
135 }};
136}
137
138/// Macro rule extraction the text caption of a File / Image / Audio / Video
139macro_rules! display_file_to_text {
140 ( $msgtype:ident, $content:expr ) => {{
141 if $content
142 .filename
143 .as_ref()
144 .is_none_or(|filename| *filename == $content.body)
145 {
146 return Cow::Borrowed("");
147 }
148 $content.body.as_str()
149 }};
150}
151
152fn content_filename(msgtype: &MessageType) -> Option<String> {
153 match msgtype {
154 MessageType::Audio(content) => Some(display_file_name!(Audio, content)),
155 MessageType::File(content) => Some(display_file_name!(File, content)),
156 MessageType::Image(content) => Some(display_file_name!(Image, content)),
157 MessageType::Video(content) => Some(display_file_name!(Video, content)),
158 _ => None,
159 }
160}
161
117162/// Convert the [u64] hash to [usize] as needed.
118163fn hash_finish_usize(hasher: DefaultHasher) -> Option<usize> {
119164 if USIZE_TOO_SMALL {
@@ -131,15 +176,13 @@ fn hash_message_id(id: &MessageId) -> Option<usize> {
131176}
132177
133178/// Before the image is loaded, already display a placeholder frame of the image size.
134fn placeholder_frame(
135 text: Option<&str>,
136 outer_width: usize,
137 image_preview_size: &Size,
138) -> Option<String> {
179fn placeholder_frame(text: Option<&str>, outer_width: usize, image_preview_size: &Size) -> String {
139180 let Size { width, height } = image_preview_size;
140181 let width = usize::min(*width as usize, outer_width);
141182 if width < 2 || *height < 2 {
142 return None;
183 let mut line = "#".repeat(width);
184 line.push('\n');
185 return line.repeat(*height as usize);
143186 }
144187 let mut placeholder = "\u{230c}".to_string();
145188 placeholder.push_str(&" ".repeat(width - 2));
@@ -158,7 +201,7 @@ fn placeholder_frame(
158201 placeholder.push('\u{230e}');
159202 placeholder.push_str(&" ".repeat(width - 2));
160203 placeholder.push_str("\u{230f}\n");
161 Some(placeholder)
204 placeholder
162205}
163206
164207#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Hash)]
@@ -398,16 +441,50 @@ fn content_html(msgtype: &MessageType) -> Option<StyleTree> {
398441
399442 MessageType::Audio(content) => content.formatted.as_ref(),
400443 MessageType::File(content) => content.formatted.as_ref(),
401 MessageType::Image(content) => content.formatted.as_ref(),
402444 MessageType::Video(content) => content.formatted.as_ref(),
445
446 MessageType::Image(content) => {
447 let mut html = if let Some(FormattedBody { format: MessageFormat::Html, body }) =
448 &content.formatted
449 {
450 parse_matrix_html(body.as_str())
451 } else {
452 StyleTree { children: vec![] }
453 };
454
455 html.children
456 .insert(0, html::StyleTreeNode::Text(display_file_name!(Image, content).into()));
457
458 let src = content.source.clone();
459 html.children.insert(
460 0,
461 html::StyleTreeNode::Image(html::Image::new(src, content.info.as_deref())),
462 );
463
464 return Some(html);
465 },
403466 _ => None,
404467 };
405468
406 if let Some(FormattedBody { format: MessageFormat::Html, body }) = formatted {
469 let mut html = if let Some(FormattedBody { format: MessageFormat::Html, body }) = formatted {
407470 Some(parse_matrix_html(body.as_str()))
408471 } else {
409472 None
473 };
474
475 if let Some(filename) = content_filename(msgtype) {
476 let html = html.get_or_insert_with(|| {
477 let text = body_cow_content(msgtype).into_owned();
478 StyleTree {
479 children: vec![html::StyleTreeNode::Text(text.into())],
480 }
481 });
482
483 html.children.push(html::StyleTreeNode::Break);
484 html.children.push(html::StyleTreeNode::Text(filename.into()));
410485 }
486
487 html
411488}
412489
413490#[derive(Clone, Debug)]
@@ -417,7 +494,7 @@ pub enum MessageEvent {
417494 Original(Box<OriginalRoomMessageEvent>, MessageEdits),
418495 Redacted(OwnedEventId, Option<String>),
419496 State(Box<AnySyncStateEvent>),
420 Sticker(Box<OriginalStickerEvent>, MediaSource),
497 Sticker(Box<OriginalStickerEvent>),
421498 Local(OwnedTransactionId, SendHandle, Box<RoomMessageEventContent>),
422499 Poll(Box<Poll>),
423500 UnstablePoll(Box<UnstablePoll>),
@@ -489,10 +566,6 @@ impl MessageEvent {
489566 self.msgtype().and_then(content_html)
490567 }
491568
492 pub fn filename(&self) -> Option<String> {
493 self.msgtype().and_then(content_filename)
494 }
495
496569 pub fn mentions(&self) -> Option<&Mentions> {
497570 match self {
498571 MessageEvent::EncryptedOriginal(..) |
@@ -579,59 +652,6 @@ impl MessageEvent {
579652 }
580653}
581654
582/// Macro rule converting a File / Image / Audio / Video to its text content with the shape:
583/// `[Attached <type>: <content>[ (<human readable file size>)]]`
584macro_rules! display_file_name {
585 ( $msgtype:ident, $content:expr ) => {{
586 Some(format!(
587 "[Attached {}: {}{}]",
588 stringify!($msgtype),
589 $content.filename(),
590 $content
591 .info
592 .as_ref()
593 .map(|info| {
594 info.size
595 .map(|s| format!(" ({})", format_size(u64::from(s), DECIMAL)))
596 .unwrap_or_else(String::new)
597 })
598 .unwrap_or_else(String::new)
599 ))
600 }};
601}
602
603/// Macro rule extraction the text caption of a File / Image / Audio / Video
604macro_rules! display_file_to_text {
605 ( $msgtype:ident, $content:expr ) => {{
606 if $content
607 .filename
608 .as_ref()
609 .is_none_or(|filename| *filename == $content.body)
610 {
611 return Cow::Borrowed("");
612 }
613 $content.body.as_str()
614 }};
615}
616
617fn content_filename(msgtype: &MessageType) -> Option<String> {
618 match msgtype {
619 MessageType::Audio(content) => {
620 display_file_name!(Audio, content)
621 },
622 MessageType::File(content) => {
623 display_file_name!(File, content)
624 },
625 MessageType::Image(content) => {
626 display_file_name!(Image, content)
627 },
628 MessageType::Video(content) => {
629 display_file_name!(Video, content)
630 },
631 _ => None,
632 }
633}
634
635655fn body_cow_content(msgtype: &MessageType) -> Cow<'_, str> {
636656 let s = match msgtype {
637657 MessageType::Text(content) => content.body.as_str(),
@@ -865,7 +885,7 @@ impl<'a> MessageFormatter<'a> {
865885 info: &'a RoomInfo,
866886 settings: &'a ApplicationSettings,
867887 previews: &'a PreviewManager,
868 ) -> Option<ProtocolPreview> {
888 ) -> Vec<ProtocolPreview> {
869889 let reply_style = if settings.tunables.message_user_color {
870890 style.patch(settings.get_user_color(&msg.sender))
871891 } else {
@@ -894,12 +914,15 @@ impl<'a> MessageFormatter<'a> {
894914 );
895915
896916 // Determine the image offset of the reply header, taking into account the formatting
897 let proto = proto.map(|p| {
898 let y_off = text.lines.len() as u16;
899 // Adjust x_off by 2 to account for the vertical line and indent
900 let x_off = self.cols.user_gutter_width(settings) + 2;
901 (p, x_off, y_off)
902 });
917 let proto = proto
918 .into_iter()
919 .map(|(p, x, y)| {
920 let y_off = text.lines.len() as u16;
921 // Adjust x_off by 2 to account for the vertical line and indent
922 let x_off = self.cols.user_gutter_width(settings) + 2;
923 (p, x + x_off, y + y_off)
924 })
925 .collect();
903926
904927 for line in replied.lines.iter_mut() {
905928 line.spans.insert(0, Span::styled(THICK_VERTICAL, style));
@@ -919,25 +942,28 @@ impl<'a> MessageFormatter<'a> {
919942 settings: &ApplicationSettings,
920943 previews: &'a PreviewManager,
921944 ) -> Vec<ProtocolPreview> {
922 let mut emojis = printer::TextPrinter::new(self.width(), style, self.settings, self.info);
945 let mut emojis = printer::TextPrinter::new(
946 self.width(),
947 style,
948 self.settings,
949 self.info,
950 Some(previews),
951 );
923952 let mut reactions = 0;
924 let mut protos = Vec::new();
925953
926954 for (key, count, source) in counts {
927955 if reactions != 0 {
928956 emojis.push_str(" ", style);
929957 }
930958
931 let proto = match source
932 .as_ref()
933 .and_then(|source| previews.get(source, PreviewKind::Reaction))
934 {
935 Some(ImageStatus::Loaded(backend)) => Some(Some(backend)),
936 // Use empty space as placeholder
937 Some(ImageStatus::Queued(_)) | Some(ImageStatus::Downloading(_)) => Some(None),
938 // Fall back to text
939 None | Some(ImageStatus::Error(_)) => None,
940 };
959 let proto =
960 match source.as_ref().and_then(|source| previews.get(source, PreviewKind::Emoji)) {
961 Some(ImageStatus::Loaded(backend)) => Some(Some(backend)),
962 // Use empty space as placeholder
963 Some(ImageStatus::Queued(_)) | Some(ImageStatus::Downloading(_)) => Some(None),
964 // Fall back to text
965 None | Some(ImageStatus::Error(_)) => None,
966 };
941967
942968 let name = if proto.is_some() {
943969 " "
@@ -961,15 +987,10 @@ impl<'a> MessageFormatter<'a> {
961987
962988 emojis.push_str("[", style);
963989 if let Some(Some(proto)) = proto {
964 let proto = Arc::clone(proto);
965
966 let (x, y) = emojis.cursor_pos();
967 let y = (y + text.lines.len()) as u16;
968 let x = x as u16 + self.cols.user_gutter_width(settings);
969
970 protos.push((proto, x, y));
990 emojis.push_emoji(proto, style);
991 } else {
992 emojis.push_str(name, style);
971993 }
972 emojis.push_str(name, style);
973994 emojis.push_str(" ", style);
974995 emojis.push_span_nobreak(Span::styled(count.len().to_string(), style));
975996 emojis.push_str("]", style);
@@ -978,10 +999,17 @@ impl<'a> MessageFormatter<'a> {
978999 }
9791000
9801001 if reactions > 0 {
981 self.push_text(emojis.finish(), style, text);
982 }
1002 let (txt, protos) = emojis.finish();
1003
1004 let x_off = self.cols.user_gutter_width(settings);
1005 let y_off = text.lines.len() as u16;
9831006
984 protos
1007 self.push_text(txt, style, text);
1008
1009 protos.into_iter().map(|(p, x, y)| (p, x + x_off, y + y_off)).collect()
1010 } else {
1011 vec![]
1012 }
9851013 }
9861014
9871015 fn push_thread_reply_count(&mut self, len: usize, text: &mut Text<'a>, style: Style) {
@@ -992,7 +1020,8 @@ impl<'a> MessageFormatter<'a> {
9921020 // If we have threaded replies to this message, show how many.
9931021 let plural = len != 1;
9941022 let mut threaded =
995 printer::TextPrinter::new(self.width(), style, self.settings, self.info).literal(true);
1023 printer::TextPrinter::new(self.width(), style, self.settings, self.info, None)
1024 .literal(true);
9961025 let len = Span::styled(len.to_string(), style.add_modifier(StyleModifier::BOLD));
9971026 threaded.push_str(" \u{2937} ", style);
9981027 threaded.push_span_nobreak(len);
@@ -1002,7 +1031,7 @@ impl<'a> MessageFormatter<'a> {
10021031 threaded.push_str(" reply in thread", style);
10031032 }
10041033
1005 self.push_text(threaded.finish(), style, text);
1034 self.push_text(threaded.finish().0, style, text);
10061035 }
10071036}
10081037
@@ -1010,7 +1039,6 @@ pub struct Message {
10101039 pub event: MessageEvent,
10111040 pub sender: OwnedUserId,
10121041 pub timestamp: MessageTimeStamp,
1013 pub downloaded: bool,
10141042 pub html: Option<StyleTree>,
10151043}
10161044
@@ -1029,9 +1057,8 @@ fn is_after_read_marker(prev: Option<&Message>, marker: Option<&OwnedEventId>) -
10291057impl Message {
10301058 pub fn new(event: MessageEvent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self {
10311059 let html = event.html();
1032 let downloaded = false;
10331060
1034 Message { event, sender, timestamp, downloaded, html }
1061 Message { event, sender, timestamp, html }
10351062 }
10361063
10371064 pub fn reply_to(&self) -> Option<OwnedEventId> {
@@ -1093,15 +1120,11 @@ impl Message {
10931120 }
10941121 }
10951122
1096 pub fn image_preview(&self) -> Option<&MediaSource> {
1097 if let Some(MessageType::Image(c)) = self.event.msgtype() {
1098 return Some(&c.source);
1099 }
1100
1101 match &self.event {
1102 MessageEvent::Sticker(_, source) => Some(source),
1103
1104 _ => None,
1123 pub fn image_previews(&self) -> Vec<(&MediaSource, PreviewKind)> {
1124 if let Some(html) = &self.html {
1125 html.image_previews()
1126 } else {
1127 vec![]
11051128 }
11061129 }
11071130
@@ -1315,10 +1338,7 @@ impl Message {
13151338 if let Some(r) = reply {
13161339 if let Some(r) = r {
13171340 // Format the reply header, push it into the `Text` buffer, and get any image.
1318 let proto_reply = fmt.push_in_reply(r, style, &mut text, info, settings, previews);
1319 if let Some(proto) = proto_reply {
1320 protos.push(proto)
1321 }
1341 protos = fmt.push_in_reply(r, style, &mut text, info, settings, previews);
13221342 } else {
13231343 fmt.push_spans(
13241344 Line::from(vec![
@@ -1337,13 +1357,16 @@ impl Message {
13371357 let (msg, proto) = self.show_msg(width, style, settings, previews, info);
13381358
13391359 // Given our text so far, determine the image offset.
1340 if let Some(p) = proto {
1360 {
13411361 let y_off = text.lines.len() as u16;
13421362 let x_off = fmt.cols.user_gutter_width(settings);
13431363
13441364 // Account for extra lines printed before the message;
13451365 let y_off = y_off + fmt.message_start_line();
1346 protos.push((p, x_off, y_off));
1366
1367 for (p, x, y) in proto {
1368 protos.push((p, x + x_off, y + y_off));
1369 }
13471370 }
13481371
13491372 fmt.push_text(msg, style, &mut text);
@@ -1405,44 +1428,16 @@ impl Message {
14051428 settings: &'a ApplicationSettings,
14061429 previews: &'a PreviewManager,
14071430 info: &'a RoomInfo,
1408 ) -> (Text<'a>, Option<Arc<SlicedProtocol>>) {
1409 let mut proto = None;
1410 let placeholder = match self
1411 .image_preview()
1412 .and_then(|source| previews.get(source, PreviewKind::Message))
1413 {
1414 None => None,
1415 Some(ImageStatus::Queued(image_preview_size)) => {
1416 placeholder_frame(Some("Queued..."), width, image_preview_size)
1417 },
1418 Some(ImageStatus::Downloading(image_preview_size)) => {
1419 placeholder_frame(Some("Downloading..."), width, image_preview_size)
1420 },
1421 Some(ImageStatus::Loaded(backend)) => {
1422 proto = Some(Arc::clone(backend));
1423 placeholder_frame(None, width, &backend.size())
1424 },
1425 Some(ImageStatus::Error(err)) => Some(format!("[Image error: {err}]\n")),
1426 };
1427
1428 let mut text = if let Some(placeholder) = placeholder {
1429 wrapped_text(placeholder, width, style)
1430 } else {
1431 Default::default()
1432 };
1433
1434 if let Some(mut filename) = self.event.filename() {
1435 if self.downloaded {
1436 filename.push_str(" \u{2705}");
1437 }
1438
1439 text += wrapped_text(filename, width, style);
1440 }
1431 ) -> (Text<'a>, Vec<ProtocolPreview>) {
1432 let mut protos = vec![];
14411433
1434 let mut text = Default::default();
14421435 if let Some(html) = &self.html &&
14431436 settings.tunables.message_formatted_display
14441437 {
1445 text += html.to_text(width, style, settings, info);
1438 let (t, p) = html.render(width, style, settings, info, previews);
1439 text += t;
1440 protos = p;
14461441 } else {
14471442 let mut msg = self.event.body();
14481443 if settings.tunables.message_shortcode_display {
@@ -1451,7 +1446,7 @@ impl Message {
14511446 text += wrapped_text(msg, width, style);
14521447 };
14531448
1454 (text, proto)
1449 (text, protos)
14551450 }
14561451
14571452 fn sender_span<'a>(
@@ -1502,7 +1497,6 @@ impl Message {
15021497 pub fn redact(&mut self, redaction: SyncRoomRedactionEvent) {
15031498 self.event.redact(redaction);
15041499 self.html = None;
1505 self.downloaded = false;
15061500 }
15071501
15081502 pub fn set_edits(&mut self, new_edits: MessageEdits) {
@@ -1656,9 +1650,21 @@ impl From<OriginalStickerEvent> for Message {
16561650 let timestamp = event.origin_server_ts.into();
16571651 let user_id = event.sender.clone();
16581652 let source = event.content.source.clone().into();
1659 let content = MessageEvent::Sticker(event.into(), source);
16601653
1661 Message::new(content, user_id, timestamp)
1654 let html_image =
1655 html::StyleTreeNode::Image(html::Image::new(source, Some(&event.content.info)));
1656
1657 let content = MessageEvent::Sticker(event.into());
1658 let mut msg = Message::new(content, user_id, timestamp);
1659
1660 msg.html = Some(StyleTree {
1661 children: vec![
1662 html::StyleTreeNode::Text("* sent a sticker:".into()),
1663 html_image,
1664 ],
1665 });
1666
1667 msg
16621668 }
16631669}
16641670
@@ -1850,8 +1856,8 @@ pub mod tests {
18501856
18511857 #[test]
18521858 fn test_placeholder_frame() {
1853 fn pretty_frame_test(str: &str) -> Option<String> {
1854 Some(str[1..].to_string())
1859 fn pretty_frame_test(str: &str) -> String {
1860 str[1..].to_string()
18551861 }
18561862
18571863 assert_eq!(
@@ -1877,9 +1883,9 @@ pub mod tests {
18771883"#
18781884 )
18791885 );
1880 assert_eq!(placeholder_frame(None, 4, &Size { width: 1, height: 4 }), None);
1886 assert_eq!(placeholder_frame(None, 4, &Size { width: 1, height: 4 }), "#\n#\n#\n#\n");
18811887
1882 assert_eq!(placeholder_frame(None, 4, &Size { width: 4, height: 1 }), None);
1888 assert_eq!(placeholder_frame(None, 4, &Size { width: 4, height: 1 }), "####\n");
18831889
18841890 assert_eq!(
18851891 placeholder_frame(Some("OK"), 4, &Size { width: 4, height: 4 }),
src/message/printer.rs +33 −10
@@ -5,6 +5,7 @@
55//! contents).
66
77use crate::base::RoomInfo;
8use crate::message::ProtocolPreview;
89use crate::prelude::*;
910use crate::util::{
1011 replace_emojis_in_line,
@@ -18,6 +19,7 @@ use crate::util::{
1819/// Wrap styled text for the current terminal width.
1920pub struct TextPrinter<'a> {
2021 text: Text<'a>,
22 images: Vec<ProtocolPreview>,
2123 width: usize,
2224 base_style: Style,
2325
@@ -28,6 +30,7 @@ pub struct TextPrinter<'a> {
2830
2931 pub(super) settings: &'a ApplicationSettings,
3032 pub(super) info: &'a RoomInfo,
33 pub(super) previews: Option<&'a PreviewManager>,
3134}
3235
3336impl<'a> TextPrinter<'a> {
@@ -37,9 +40,11 @@ impl<'a> TextPrinter<'a> {
3740 base_style: Style,
3841 settings: &'a ApplicationSettings,
3942 info: &'a RoomInfo,
43 previews: Option<&'a PreviewManager>,
4044 ) -> Self {
4145 TextPrinter {
4246 text: Text::default(),
47 images: vec![],
4348 width,
4449 base_style,
4550
@@ -49,14 +54,10 @@ impl<'a> TextPrinter<'a> {
4954 literal: false,
5055 settings,
5156 info,
57 previews,
5258 }
5359 }
5460
55 /// The `(x, y)` position where the next text will be printed.
56 pub fn cursor_pos(&self) -> (usize, usize) {
57 (self.curr_width, self.text.lines.len())
58 }
59
6061 /// Configure the alignment for each line.
6162 pub fn align(mut self, alignment: Alignment) -> Self {
6263 self.alignment = alignment;
@@ -96,6 +97,7 @@ impl<'a> TextPrinter<'a> {
9697 pub fn sub(&self, indent: usize) -> Self {
9798 TextPrinter {
9899 text: Text::default(),
100 images: vec![],
99101 width: self.width.saturating_sub(indent),
100102 base_style: self.base_style,
101103
@@ -105,6 +107,7 @@ impl<'a> TextPrinter<'a> {
105107 literal: self.literal,
106108 settings: self.settings,
107109 info: self.info,
110 previews: self.previews,
108111 }
109112 }
110113
@@ -306,10 +309,29 @@ impl<'a> TextPrinter<'a> {
306309 self.text.lines.extend(text.lines);
307310 }
308311
312 /// Push an image that will be forced into an Emoji size (1 row, 2 columns).
313 pub fn push_emoji(&mut self, image: &Arc<SlicedProtocol>, style: Style) {
314 if self.curr_width + 2 > self.width {
315 self.commit();
316 }
317
318 self.push_image(image);
319 self.curr_spans.push(Span::styled(" ", style));
320 self.curr_width += 2;
321 }
322
323 /// Push an image without placeholder
324 pub fn push_image(&mut self, image: &Arc<SlicedProtocol>) {
325 let y = self.text.lines.len() as u16;
326 let x = self.curr_width as u16;
327
328 self.images.push((Arc::clone(image), x, y));
329 }
330
309331 /// Render the contents of this printer as [Text].
310 pub fn finish(mut self) -> Text<'a> {
332 pub fn finish(mut self) -> (Text<'a>, Vec<ProtocolPreview>) {
311333 self.commit();
312 self.text
334 (self.text, self.images)
313335 }
314336}
315337
@@ -323,9 +345,9 @@ pub mod tests {
323345 fn test_push_nobreak() {
324346 let settings = mock_settings();
325347 let info = mock_room();
326 let mut printer = TextPrinter::new(5, Style::default(), &settings, &info);
348 let mut printer = TextPrinter::new(5, Style::default(), &settings, &info, None);
327349 printer.push_span_nobreak("hello world".into());
328 let text = printer.finish();
350 let text = printer.finish().0;
329351 assert_eq!(text.lines.len(), 1);
330352 assert_eq!(text.lines[0].spans.len(), 1);
331353 assert_eq!(text.lines[0].spans[0].content, "hello world");
@@ -335,10 +357,11 @@ pub mod tests {
335357 fn test_push_str_wide_char_wider_than_width() {
336358 let settings = mock_settings();
337359 let info = mock_room();
338 let mut printer = TextPrinter::new(1, Style::default(), &settings, &info);
360 let mut printer = TextPrinter::new(1, Style::default(), &settings, &info, None);
339361 printer.push_str("a世b", Style::default());
340362 let text = printer.finish();
341363 let lines: Vec<String> = text
364 .0
342365 .lines
343366 .iter()
344367 .map(|line| line.spans.iter().map(|span| span.content.as_ref()).collect())
src/prelude.rs +1
@@ -68,6 +68,7 @@ pub use ratatui::layout::{Alignment, Rect, Size};
6868pub use ratatui::style::{Color, Modifier as StyleModifier, Style};
6969pub use ratatui::text::{Line, Span, Text};
7070pub use ratatui::widgets::{Paragraph, StatefulWidget, Widget};
71pub use ratatui_image::sliced::SlicedProtocol;
7172pub use unicode_segmentation::UnicodeSegmentation;
7273pub use unicode_width::UnicodeWidthStr;
7374pub use url::Url;
src/preview.rs +37 −7
@@ -1,7 +1,6 @@
11use matrix_sdk::Media;
22use matrix_sdk::media::{MediaFormat, MediaRequestParameters, UniqueKey};
33use ratatui_image::picker::Picker;
4use ratatui_image::sliced::SlicedProtocol;
54use ratatui_image::{FilterType, Resize};
65use tokio::sync::Semaphore;
76
@@ -17,15 +16,46 @@ pub enum ImageStatus {
1716
1817#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1918pub enum PreviewKind {
20 Message,
21 Reaction,
19 /// A custom `width, height` is given in pixels or defaults to the config
20 Custom(Option<u16>, Option<u16>),
21
22 /// Force the image to be rendered in Emoji presentation (i.e., 1x2 characters)
23 ///
24 /// This is used primarily for custom message reactions and for the `data-mx-emoticon`
25 /// attribute on images, which is typically used when forcing stickers to appear like
26 /// custom Emoji.
27 ///
28 /// In the future, we could potentially investigate using this as a way to also handle
29 /// troublesome ZWJ combinations that confuse terminals or ratatui by not having clear
30 /// widths across implementations.
31 Emoji,
32}
33
34impl Default for PreviewKind {
35 fn default() -> Self {
36 Self::Custom(None, None)
37 }
2238}
2339
2440impl PreviewKind {
25 fn image_size(self, image_preview: &ImagePreviewValues) -> Size {
41 fn image_size(self, picker: &Picker, image_preview: &ImagePreviewValues) -> Size {
2642 match self {
27 Self::Message => image_preview.size,
28 Self::Reaction => Size { width: 2, height: 1 },
43 Self::Emoji => Size { width: 2, height: 1 },
44 Self::Custom(width, height) => {
45 let font_size = picker.font_size();
46
47 let width = width
48 .map(|width| width.div_ceil(font_size.width))
49 .unwrap_or(image_preview.size.width)
50 .min(image_preview.size.width);
51
52 let height = height
53 .map(|height| height.div_ceil(font_size.height))
54 .unwrap_or(image_preview.size.height)
55 .min(image_preview.size.height);
56
57 Size { width, height }
58 },
2959 }
3060 }
3161}
@@ -91,7 +121,7 @@ impl PreviewManager {
91121 return;
92122 }
93123
94 let size = kind.image_size(&settings.tunables.image_preview);
124 let size = kind.image_size(&self.picker, &settings.tunables.image_preview);
95125 self.previews.insert(key, ImageStatus::Queued(size));
96126 }
97127}
src/windows/room/chat.rs +2 −4
@@ -197,7 +197,7 @@ impl ChatState {
197197 let settings = &store.application.settings;
198198 let info = store.application.rooms.get_or_default(self.room_id.clone());
199199
200 let msg = self.scrollback.get_mut(info).ok_or(IambError::NoSelectedMessage)?;
200 let msg = self.scrollback.get(info).ok_or(IambError::NoSelectedMessage)?;
201201
202202 match act {
203203 MessageAction::Cancel(skip_confirm) => {
@@ -652,7 +652,7 @@ fn open_links(msg: &Message) -> UIError<IambInfo> {
652652pub async fn msg_download(
653653 ctx: ProgramContext,
654654 client: &Client,
655 msg: &mut Message,
655 msg: &Message,
656656 settings: &ApplicationSettings,
657657 filename: Option<PathBuf>,
658658 flags: DownloadFlags,
@@ -732,8 +732,6 @@ pub async fn msg_download(
732732 let bytes = media.get_media_content(&req, true).await.map_err(IambError::from)?;
733733
734734 fs::write(filename.as_path(), bytes.as_slice())?;
735
736 msg.downloaded = true;
737735 } else if !flags.contains(DownloadFlags::OPEN) {
738736 let msg = format!(
739737 "The file {} already exists; add ! to end of command to overwrite it.",
src/windows/room/message.rs +8 −10
@@ -81,7 +81,6 @@ impl MessageState {
8181
8282 match act {
8383 MessageAction::Download(filename, flags) => {
84 let msg = info.get_message_mut(&self.id()).unwrap();
8584 chat::msg_download(
8685 ctx,
8786 &store.application.worker.client,
@@ -262,16 +261,15 @@ impl StatefulWidget for MessageWidget<'_> {
262261
263262 // load image previews
264263 {
265 if let Some(source) = msg.image_preview() {
266 previews.load(source, PreviewKind::Message, worker);
267 }
268 let reply = msg
264 let sources = msg
269265 .reply_to()
270266 .or_else(|| msg.thread_root())
271267 .and_then(|e| info.get_event(&e))
272 .and_then(|msg| msg.image_preview());
273 if let Some(source) = reply {
274 previews.load(source, PreviewKind::Message, worker);
268 .into_iter()
269 .chain(std::iter::once(msg))
270 .flat_map(|msg| msg.image_previews());
271 for (source, kind) in sources {
272 previews.load(source, kind, worker);
275273 }
276274 let reactions =
277275 msg.event.event_id().and_then(|event_id| info.reactions.get(event_id)).map(
@@ -279,7 +277,7 @@ impl StatefulWidget for MessageWidget<'_> {
279277 );
280278 if let Some(reactions) = reactions {
281279 for source in reactions {
282 previews.load(source, PreviewKind::Reaction, worker);
280 previews.load(source, PreviewKind::Emoji, worker);
283281 }
284282 }
285283 }
@@ -327,7 +325,7 @@ impl StatefulWidget for MessageWidget<'_> {
327325
328326 let proto = match source
329327 .as_ref()
330 .and_then(|source| previews.get(source, PreviewKind::Reaction))
328 .and_then(|source| previews.get(source, PreviewKind::Emoji))
331329 {
332330 Some(ImageStatus::Loaded(backend)) => Some(Some(backend)),
333331 // Use empty space as placeholder
src/windows/room/scrollback.rs +7 −26
@@ -158,16 +158,6 @@ impl ScrollbackState {
158158 }
159159 }
160160
161 pub fn get_mut<'a>(&mut self, info: &'a mut RoomInfo) -> Option<&'a mut Message> {
162 let thread = self.get_thread_mut(info);
163
164 if let Some(k) = &self.cursor.timestamp {
165 thread.get_mut(k)
166 } else {
167 thread.last_entry().map(|o| o.into_mut())
168 }
169 }
170
171161 pub fn thread(&self) -> Option<&OwnedEventId> {
172162 self.thread.as_ref()
173163 }
@@ -176,10 +166,6 @@ impl ScrollbackState {
176166 info.get_thread(self.thread.as_deref())
177167 }
178168
179 pub fn get_thread_mut<'a>(&self, info: &'a mut RoomInfo) -> &'a mut Messages {
180 info.get_thread_mut(self.thread.clone())
181 }
182
183169 pub fn messages<'a>(
184170 &self,
185171 range: EditRange<MessageCursor>,
@@ -1368,22 +1354,17 @@ impl StatefulWidget for Scrollback<'_> {
13681354 // load image previews
13691355 if settings.tunables.image_preview.enabled {
13701356 for (key, item) in thread.range(&corner_key..).rev() {
1371 if let Some(source) = item.image_preview() {
1372 self.store.application.previews.load(
1373 source,
1374 PreviewKind::Message,
1375 &self.store.application.worker,
1376 );
1377 }
1378 let reply = item
1357 let previews = item
13791358 .reply_to()
13801359 .or_else(|| item.thread_root())
13811360 .and_then(|e| info.get_event(&e))
1382 .and_then(|msg| msg.image_preview());
1383 if let Some(source) = reply {
1361 .into_iter()
1362 .chain(std::iter::once(item))
1363 .flat_map(|msg| msg.image_previews());
1364 for (source, kind) in previews {
13841365 self.store.application.previews.load(
13851366 source,
1386 PreviewKind::Message,
1367 kind,
13871368 &self.store.application.worker,
13881369 );
13891370 }
@@ -1391,7 +1372,7 @@ impl StatefulWidget for Scrollback<'_> {
13911372 for source in info.get_reaction_images(event_id) {
13921373 self.store.application.previews.load(
13931374 source,
1394 PreviewKind::Reaction,
1375 PreviewKind::Emoji,
13951376 &self.store.application.worker,
13961377 );
13971378 }
src/worker.rs +4 −4
@@ -518,13 +518,13 @@ fn insert_msgs_and_receipts(
518518 info.insert_encrypted(msg);
519519 },
520520 AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::RoomMessage(msg)) => {
521 info.insert_with_preview(msg, settings, previews);
521 info.insert_message(msg, settings, previews);
522522 },
523523 AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Reaction(ev)) => {
524524 info.insert_reaction_with_preview(ev, settings, previews);
525525 },
526526 AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::Sticker(ev)) => {
527 info.insert_sticker_with_preview(ev, settings, previews);
527 info.insert_sticker(ev, settings, previews);
528528 },
529529 AnyTimelineEvent::MessageLike(AnyMessageLikeEvent::RoomRedaction(..)) => {
530530 // ignoring redaction events because we get them bundled with the redacted event
@@ -1805,7 +1805,7 @@ impl ClientWorker {
18051805 let info = rooms.get_or_default(room_id.to_owned());
18061806
18071807 let full_ev = ev.into_full_event(room_id.to_owned());
1808 info.insert_with_preview(full_ev, settings, previews);
1808 info.insert_message(full_ev, settings, previews);
18091809
18101810 update_event_receipts(info, &room, event_id).await;
18111811 }
@@ -1857,7 +1857,7 @@ impl ClientWorker {
18571857 let info = rooms.get_or_default(room_id.to_owned());
18581858
18591859 let full_ev = ev.into_full_event(room_id.to_owned());
1860 info.insert_sticker_with_preview(full_ev, settings, previews);
1860 info.insert_sticker(full_ev, settings, previews);
18611861
18621862 update_event_receipts(info, &room, event_id).await;
18631863 }