src/message/mod.rs
1496 lines · 48811 bytes
1//! # Room Messages
2use std::borrow::Cow;
3use std::cmp::{Ord, Ordering, PartialOrd};
4use std::collections::hash_map::DefaultHasher;
5use std::collections::hash_set;
6use std::collections::BTreeMap;
7use std::convert::TryFrom;
8use std::hash::{Hash, Hasher};
9use std::ops::{Deref, DerefMut};
10
11use chrono::{DateTime, Local as LocalTz, NaiveDateTime, TimeZone};
12use comrak::{markdown_to_html, ComrakOptions};
13use humansize::{format_size, DECIMAL};
14use serde_json::json;
15use unicode_width::UnicodeWidthStr;
16
17use matrix_sdk::ruma::{
18 events::{
19 relation::Thread,
20 room::{
21 encrypted::{
22 OriginalRoomEncryptedEvent,
23 RedactedRoomEncryptedEvent,
24 RoomEncryptedEvent,
25 },
26 message::{
27 FormattedBody,
28 MessageFormat,
29 MessageType,
30 OriginalRoomMessageEvent,
31 RedactedRoomMessageEvent,
32 Relation,
33 RoomMessageEvent,
34 RoomMessageEventContent,
35 TextMessageEventContent,
36 },
37 redaction::SyncRoomRedactionEvent,
38 },
39 RedactContent,
40 RedactedUnsigned,
41 },
42 EventId,
43 MilliSecondsSinceUnixEpoch,
44 OwnedEventId,
45 OwnedUserId,
46 RoomVersionId,
47 UInt,
48};
49
50use ratatui::{
51 style::{Modifier as StyleModifier, Style},
52 symbols::line::THICK_VERTICAL,
53 text::{Line, Span, Text},
54};
55
56use modalkit::editing::cursor::Cursor;
57use modalkit::prelude::*;
58use ratatui_image::protocol::Protocol;
59
60use crate::config::ImagePreviewSize;
61use crate::{
62 base::RoomInfo,
63 config::ApplicationSettings,
64 message::html::{parse_matrix_html, StyleTree},
65 util::{replace_emojis_in_str, space, space_span, take_width, wrapped_text},
66};
67
68mod html;
69mod printer;
70
71pub type MessageKey = (MessageTimeStamp, OwnedEventId);
72
73#[derive(Default)]
74pub struct Messages(BTreeMap<MessageKey, Message>);
75
76impl Deref for Messages {
77 type Target = BTreeMap<MessageKey, Message>;
78
79 fn deref(&self) -> &Self::Target {
80 &self.0
81 }
82}
83
84impl DerefMut for Messages {
85 fn deref_mut(&mut self) -> &mut Self::Target {
86 &mut self.0
87 }
88}
89
90impl Messages {
91 pub fn insert_message(&mut self, key: MessageKey, msg: impl Into<Message>) {
92 let event_id = key.1.clone();
93 let msg = msg.into();
94
95 self.0.insert(key, msg);
96
97 // Remove any echo.
98 let key = (MessageTimeStamp::LocalEcho, event_id);
99 let _ = self.0.remove(&key);
100 }
101}
102
103const fn span_static(s: &'static str) -> Span<'static> {
104 Span {
105 content: Cow::Borrowed(s),
106 style: Style {
107 fg: None,
108 bg: None,
109 add_modifier: StyleModifier::empty(),
110 sub_modifier: StyleModifier::empty(),
111 underline_color: None,
112 },
113 }
114}
115
116const BOLD_STYLE: Style = Style {
117 fg: None,
118 bg: None,
119 add_modifier: StyleModifier::BOLD,
120 sub_modifier: StyleModifier::empty(),
121 underline_color: None,
122};
123
124const TIME_GUTTER: usize = 12;
125const READ_GUTTER: usize = 5;
126const MIN_MSG_LEN: usize = 30;
127
128const TIME_GUTTER_EMPTY: &str = " ";
129const TIME_GUTTER_EMPTY_SPAN: Span<'static> = span_static(TIME_GUTTER_EMPTY);
130
131fn text_to_message_content(input: String) -> TextMessageEventContent {
132 let mut options = ComrakOptions::default();
133 options.extension.autolink = true;
134 options.extension.shortcodes = true;
135 options.extension.strikethrough = true;
136 options.render.hardbreaks = true;
137 let html = markdown_to_html(input.as_str(), &options);
138
139 TextMessageEventContent::html(input, html)
140}
141
142pub fn text_to_message(input: String) -> RoomMessageEventContent {
143 let msg = MessageType::Text(text_to_message_content(input));
144 RoomMessageEventContent::new(msg)
145}
146
147/// Before the image is loaded, already display a placeholder frame of the image size.
148fn placeholder_frame(
149 text: Option<&str>,
150 outer_width: usize,
151 image_preview_size: &ImagePreviewSize,
152) -> Option<String> {
153 let ImagePreviewSize { width, height } = image_preview_size;
154 if outer_width < *width || (*width < 2 || *height < 2) {
155 return None;
156 }
157 let mut placeholder = "\u{230c}".to_string();
158 placeholder.push_str(&" ".repeat(width - 2));
159 placeholder.push_str("\u{230d}\n");
160 if *height > 2 {
161 if let Some(text) = text {
162 if text.width() <= width - 2 {
163 placeholder.push(' ');
164 placeholder.push_str(text);
165 }
166 }
167 }
168
169 placeholder.push_str(&"\n".repeat(height - 2));
170 placeholder.push('\u{230e}');
171 placeholder.push_str(&" ".repeat(width - 2));
172 placeholder.push_str("\u{230f}\n");
173 Some(placeholder)
174}
175
176#[inline]
177fn millis_to_datetime(ms: UInt) -> DateTime<LocalTz> {
178 let time = i64::from(ms) / 1000;
179 let time = NaiveDateTime::from_timestamp_opt(time, 0).unwrap_or_default();
180
181 LocalTz.from_utc_datetime(&time)
182}
183
184#[derive(thiserror::Error, Debug)]
185pub enum TimeStampIntError {
186 #[error("Integer conversion error: {0}")]
187 IntError(#[from] std::num::TryFromIntError),
188
189 #[error("UInt conversion error: {0}")]
190 UIntError(<UInt as TryFrom<u64>>::Error),
191}
192
193#[derive(Clone, Copy, Debug, Eq, PartialEq)]
194pub enum MessageTimeStamp {
195 OriginServer(UInt),
196 LocalEcho,
197}
198
199impl MessageTimeStamp {
200 fn as_datetime(&self) -> DateTime<LocalTz> {
201 match self {
202 MessageTimeStamp::OriginServer(ms) => millis_to_datetime(*ms),
203 MessageTimeStamp::LocalEcho => LocalTz::now(),
204 }
205 }
206
207 fn same_day(&self, other: &Self) -> bool {
208 let dt1 = self.as_datetime();
209 let dt2 = other.as_datetime();
210
211 dt1.date_naive() == dt2.date_naive()
212 }
213
214 fn show_date(&self) -> Option<Span> {
215 let time = self.as_datetime().format("%A, %B %d %Y").to_string();
216
217 Span::styled(time, BOLD_STYLE).into()
218 }
219
220 fn show_time(&self) -> Option<Span> {
221 match self {
222 MessageTimeStamp::OriginServer(ms) => {
223 let time = millis_to_datetime(*ms).format("%T");
224 let time = format!(" [{time}]");
225
226 Span::raw(time).into()
227 },
228 MessageTimeStamp::LocalEcho => None,
229 }
230 }
231
232 fn is_local_echo(&self) -> bool {
233 matches!(self, MessageTimeStamp::LocalEcho)
234 }
235
236 pub fn as_millis(&self) -> Option<MilliSecondsSinceUnixEpoch> {
237 match self {
238 MessageTimeStamp::OriginServer(ms) => MilliSecondsSinceUnixEpoch(*ms).into(),
239 MessageTimeStamp::LocalEcho => None,
240 }
241 }
242}
243
244impl Ord for MessageTimeStamp {
245 fn cmp(&self, other: &Self) -> Ordering {
246 match (self, other) {
247 (MessageTimeStamp::OriginServer(_), MessageTimeStamp::LocalEcho) => Ordering::Less,
248 (MessageTimeStamp::OriginServer(a), MessageTimeStamp::OriginServer(b)) => a.cmp(b),
249 (MessageTimeStamp::LocalEcho, MessageTimeStamp::OriginServer(_)) => Ordering::Greater,
250 (MessageTimeStamp::LocalEcho, MessageTimeStamp::LocalEcho) => Ordering::Equal,
251 }
252 }
253}
254
255impl PartialOrd for MessageTimeStamp {
256 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
257 Some(self.cmp(other))
258 }
259}
260
261impl From<UInt> for MessageTimeStamp {
262 fn from(millis: UInt) -> Self {
263 MessageTimeStamp::OriginServer(millis)
264 }
265}
266
267impl From<MilliSecondsSinceUnixEpoch> for MessageTimeStamp {
268 fn from(millis: MilliSecondsSinceUnixEpoch) -> Self {
269 MessageTimeStamp::OriginServer(millis.0)
270 }
271}
272
273impl TryFrom<&MessageTimeStamp> for usize {
274 type Error = TimeStampIntError;
275
276 fn try_from(ts: &MessageTimeStamp) -> Result<Self, Self::Error> {
277 let n = match ts {
278 MessageTimeStamp::LocalEcho => 0,
279 MessageTimeStamp::OriginServer(u) => usize::try_from(u64::from(*u))?,
280 };
281
282 Ok(n)
283 }
284}
285
286impl TryFrom<usize> for MessageTimeStamp {
287 type Error = TimeStampIntError;
288
289 fn try_from(u: usize) -> Result<Self, Self::Error> {
290 if u == 0 {
291 Ok(MessageTimeStamp::LocalEcho)
292 } else {
293 let n = u64::try_from(u)?;
294 let n = UInt::try_from(n).map_err(TimeStampIntError::UIntError)?;
295
296 Ok(MessageTimeStamp::from(n))
297 }
298 }
299}
300
301#[derive(Clone, Debug, Default, Eq, PartialEq)]
302pub struct MessageCursor {
303 /// When timestamp is None, the corner is determined by moving backwards from
304 /// the most recently received message.
305 pub timestamp: Option<MessageKey>,
306
307 /// A row within the [Text] representation of a [Message].
308 pub text_row: usize,
309}
310
311impl MessageCursor {
312 pub fn new(timestamp: MessageKey, text_row: usize) -> Self {
313 MessageCursor { timestamp: Some(timestamp), text_row }
314 }
315
316 /// Get a cursor that refers to the most recent message.
317 pub fn latest() -> Self {
318 MessageCursor::default()
319 }
320
321 pub fn to_key<'a>(&'a self, thread: &'a Messages) -> Option<&'a MessageKey> {
322 if let Some(ref key) = self.timestamp {
323 Some(key)
324 } else {
325 Some(thread.last_key_value()?.0)
326 }
327 }
328
329 pub fn from_cursor(cursor: &Cursor, thread: &Messages) -> Option<Self> {
330 let ev_hash = u64::try_from(cursor.get_x()).ok()?;
331 let ev_term = OwnedEventId::try_from("$").ok()?;
332
333 let ts_start = MessageTimeStamp::try_from(cursor.get_y()).ok()?;
334 let start = (ts_start, ev_term);
335
336 for ((ts, event_id), _) in thread.range(&start..) {
337 let mut hasher = DefaultHasher::new();
338 event_id.hash(&mut hasher);
339
340 if hasher.finish() == ev_hash {
341 return Self::from((*ts, event_id.clone())).into();
342 }
343
344 if ts > &ts_start {
345 break;
346 }
347 }
348
349 // If we can't find the cursor, then go to the nearest timestamp.
350 thread
351 .range(start..)
352 .next()
353 .map(|((ts, ev), _)| Self::from((*ts, ev.clone())))
354 }
355
356 pub fn to_cursor(&self, thread: &Messages) -> Option<Cursor> {
357 let (ts, event_id) = self.to_key(thread)?;
358
359 let y: usize = usize::try_from(ts).ok()?;
360
361 let mut hasher = DefaultHasher::new();
362 event_id.hash(&mut hasher);
363 let x = usize::try_from(hasher.finish()).ok()?;
364
365 Cursor::new(y, x).into()
366 }
367}
368
369impl From<Option<MessageKey>> for MessageCursor {
370 fn from(key: Option<MessageKey>) -> Self {
371 MessageCursor { timestamp: key, text_row: 0 }
372 }
373}
374
375impl From<MessageKey> for MessageCursor {
376 fn from(key: MessageKey) -> Self {
377 MessageCursor { timestamp: Some(key), text_row: 0 }
378 }
379}
380
381impl Ord for MessageCursor {
382 fn cmp(&self, other: &Self) -> Ordering {
383 match (&self.timestamp, &other.timestamp) {
384 (None, None) => self.text_row.cmp(&other.text_row),
385 (None, Some(_)) => Ordering::Greater,
386 (Some(_), None) => Ordering::Less,
387 (Some(st), Some(ot)) => {
388 let pcmp = st.cmp(ot);
389 let tcmp = self.text_row.cmp(&other.text_row);
390
391 pcmp.then(tcmp)
392 },
393 }
394 }
395}
396
397impl PartialOrd for MessageCursor {
398 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
399 Some(self.cmp(other))
400 }
401}
402
403fn redaction_reason(ev: &SyncRoomRedactionEvent) -> Option<&str> {
404 let SyncRoomRedactionEvent::Original(ev) = ev else {
405 return None;
406 };
407
408 return ev.content.reason.as_deref();
409}
410
411fn redaction_unsigned(ev: SyncRoomRedactionEvent) -> RedactedUnsigned {
412 let reason = redaction_reason(&ev);
413 let redacted_because = json!({
414 "content": {
415 "reason": reason
416 },
417 "event_id": ev.event_id(),
418 "sender": ev.sender(),
419 "origin_server_ts": ev.origin_server_ts(),
420 "unsigned": {},
421 });
422 RedactedUnsigned::new(serde_json::from_value(redacted_because).unwrap())
423}
424
425#[derive(Clone)]
426pub enum MessageEvent {
427 EncryptedOriginal(Box<OriginalRoomEncryptedEvent>),
428 EncryptedRedacted(Box<RedactedRoomEncryptedEvent>),
429 Original(Box<OriginalRoomMessageEvent>),
430 Redacted(Box<RedactedRoomMessageEvent>),
431 Local(OwnedEventId, Box<RoomMessageEventContent>),
432}
433
434impl MessageEvent {
435 pub fn event_id(&self) -> &EventId {
436 match self {
437 MessageEvent::EncryptedOriginal(ev) => ev.event_id.as_ref(),
438 MessageEvent::EncryptedRedacted(ev) => ev.event_id.as_ref(),
439 MessageEvent::Original(ev) => ev.event_id.as_ref(),
440 MessageEvent::Redacted(ev) => ev.event_id.as_ref(),
441 MessageEvent::Local(event_id, _) => event_id.as_ref(),
442 }
443 }
444
445 pub fn content(&self) -> Option<&RoomMessageEventContent> {
446 match self {
447 MessageEvent::EncryptedOriginal(_) => None,
448 MessageEvent::Original(ev) => Some(&ev.content),
449 MessageEvent::EncryptedRedacted(_) => None,
450 MessageEvent::Redacted(_) => None,
451 MessageEvent::Local(_, content) => Some(content),
452 }
453 }
454
455 pub fn is_emote(&self) -> bool {
456 matches!(
457 self.content(),
458 Some(RoomMessageEventContent { msgtype: MessageType::Emote(_), .. })
459 )
460 }
461
462 pub fn body(&self) -> Cow<'_, str> {
463 match self {
464 MessageEvent::EncryptedOriginal(_) => "[Unable to decrypt message]".into(),
465 MessageEvent::Original(ev) => body_cow_content(&ev.content),
466 MessageEvent::EncryptedRedacted(ev) => body_cow_reason(&ev.unsigned),
467 MessageEvent::Redacted(ev) => body_cow_reason(&ev.unsigned),
468 MessageEvent::Local(_, content) => body_cow_content(content),
469 }
470 }
471
472 pub fn html(&self) -> Option<StyleTree> {
473 let content = match self {
474 MessageEvent::EncryptedOriginal(_) => return None,
475 MessageEvent::EncryptedRedacted(_) => return None,
476 MessageEvent::Original(ev) => &ev.content,
477 MessageEvent::Redacted(_) => return None,
478 MessageEvent::Local(_, content) => content,
479 };
480
481 if let MessageType::Text(content) = &content.msgtype {
482 if let Some(FormattedBody { format: MessageFormat::Html, body }) = &content.formatted {
483 Some(parse_matrix_html(body.as_str()))
484 } else {
485 None
486 }
487 } else {
488 None
489 }
490 }
491
492 fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
493 match self {
494 MessageEvent::EncryptedOriginal(_) => return,
495 MessageEvent::EncryptedRedacted(_) => return,
496 MessageEvent::Redacted(_) => return,
497 MessageEvent::Local(_, _) => return,
498 MessageEvent::Original(ev) => {
499 let redacted = RedactedRoomMessageEvent {
500 content: ev.content.clone().redact(version),
501 event_id: ev.event_id.clone(),
502 sender: ev.sender.clone(),
503 origin_server_ts: ev.origin_server_ts,
504 room_id: ev.room_id.clone(),
505 unsigned: redaction_unsigned(redaction),
506 };
507 *self = MessageEvent::Redacted(Box::new(redacted));
508 },
509 }
510 }
511}
512
513/// Macro rule converting a File / Image / Audio / Video to its text content with the shape:
514/// `[Attached <type>: <content>[ (<human readable file size>)]]`
515macro_rules! display_file_to_text {
516 ( $msgtype:ident, $content:expr ) => {
517 return Cow::Owned(format!(
518 "[Attached {}: {}{}]",
519 stringify!($msgtype),
520 $content.body,
521 $content
522 .info
523 .as_ref()
524 .map(|info| {
525 info.size
526 .map(|s| format!(" ({})", format_size(u64::from(s), DECIMAL)))
527 .unwrap_or_else(String::new)
528 })
529 .unwrap_or_else(String::new)
530 ))
531 };
532}
533
534fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
535 let s = match &content.msgtype {
536 MessageType::Text(content) => content.body.as_str(),
537 MessageType::VerificationRequest(_) => "[Verification Request]",
538 MessageType::Emote(content) => content.body.as_ref(),
539 MessageType::Notice(content) => content.body.as_str(),
540 MessageType::ServerNotice(content) => content.body.as_str(),
541
542 MessageType::Audio(content) => {
543 display_file_to_text!(Audio, content);
544 },
545 MessageType::File(content) => {
546 display_file_to_text!(File, content);
547 },
548 MessageType::Image(content) => {
549 display_file_to_text!(Image, content);
550 },
551 MessageType::Video(content) => {
552 display_file_to_text!(Video, content);
553 },
554 _ => {
555 return Cow::Owned(format!("[Unknown message type: {:?}]", content.msgtype()));
556 },
557 };
558
559 Cow::Borrowed(s)
560}
561
562fn body_cow_reason(unsigned: &RedactedUnsigned) -> Cow<'_, str> {
563 let reason = unsigned.redacted_because.content.reason.as_ref();
564
565 if let Some(r) = reason {
566 Cow::Owned(format!("[Redacted: {r:?}]"))
567 } else {
568 Cow::Borrowed("[Redacted]")
569 }
570}
571
572enum MessageColumns {
573 /// Four columns: sender, message, timestamp, read receipts.
574 Four,
575
576 /// Three columns: sender, message, timestamp.
577 Three,
578
579 /// Two columns: sender, message.
580 Two,
581
582 /// One column: message with sender on line before the message.
583 One,
584}
585
586impl MessageColumns {
587 fn user_gutter_width(&self, settings: &ApplicationSettings) -> u16 {
588 if let MessageColumns::One = self {
589 0
590 } else {
591 settings.tunables.user_gutter_width as u16
592 }
593 }
594}
595
596struct MessageFormatter<'a> {
597 settings: &'a ApplicationSettings,
598
599 /// How many columns to print.
600 cols: MessageColumns,
601
602 /// The full, original width.
603 orig: usize,
604
605 /// The width that the message contents need to fill.
606 fill: usize,
607
608 /// The formatted Span for the message sender.
609 user: Option<Span<'a>>,
610
611 /// The time the message was sent.
612 time: Option<Span<'a>>,
613
614 /// The date the message was sent.
615 date: Option<Span<'a>>,
616
617 /// Iterator over the users who have read up to this message.
618 read: Option<hash_set::Iter<'a, OwnedUserId>>,
619}
620
621impl<'a> MessageFormatter<'a> {
622 fn width(&self) -> usize {
623 self.fill
624 }
625
626 #[inline]
627 fn push_spans(&mut self, prev_line: Line<'a>, style: Style, text: &mut Text<'a>) {
628 if let Some(date) = self.date.take() {
629 let len = date.content.as_ref().len();
630 let padding = self.orig.saturating_sub(len);
631 let leading = space_span(padding / 2, Style::default());
632 let trailing = space_span(padding.saturating_sub(padding / 2), Style::default());
633
634 text.lines.push(Line::from(vec![leading, date, trailing]));
635 }
636
637 let user_gutter_empty_span =
638 space_span(self.settings.tunables.user_gutter_width, Style::default());
639
640 match self.cols {
641 MessageColumns::Four => {
642 let settings = self.settings;
643 let user = self.user.take().unwrap_or(user_gutter_empty_span);
644 let time = self.time.take().unwrap_or(TIME_GUTTER_EMPTY_SPAN);
645
646 let mut line = vec![user];
647 line.extend(prev_line.spans);
648 line.push(time);
649
650 // Show read receipts.
651 let user_char =
652 |user: &'a OwnedUserId| -> Span<'a> { settings.get_user_char_span(user) };
653 let mut read = self.read.iter_mut().flatten();
654
655 let a = read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
656 let b = read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
657 let c = read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
658
659 line.push(Span::raw(" "));
660 line.push(c);
661 line.push(b);
662 line.push(a);
663 line.push(Span::raw(" "));
664
665 text.lines.push(Line::from(line))
666 },
667 MessageColumns::Three => {
668 let user = self.user.take().unwrap_or(user_gutter_empty_span);
669 let time = self.time.take().unwrap_or_else(|| Span::from(""));
670
671 let mut line = vec![user];
672 line.extend(prev_line.spans);
673 line.push(time);
674
675 text.lines.push(Line::from(line))
676 },
677 MessageColumns::Two => {
678 let user = self.user.take().unwrap_or(user_gutter_empty_span);
679 let mut line = vec![user];
680 line.extend(prev_line.spans);
681
682 text.lines.push(Line::from(line));
683 },
684 MessageColumns::One => {
685 if let Some(user) = self.user.take() {
686 text.lines.push(Line::from(vec![user]));
687 }
688
689 let leading = space_span(2, style);
690 let mut line = vec![leading];
691 line.extend(prev_line.spans);
692
693 text.lines.push(Line::from(line));
694 },
695 }
696 }
697
698 fn push_text(&mut self, append: Text<'a>, style: Style, text: &mut Text<'a>) {
699 for line in append.lines.into_iter() {
700 self.push_spans(line, style, text);
701 }
702 }
703
704 fn push_in_reply(
705 &mut self,
706 msg: &'a Message,
707 style: Style,
708 text: &mut Text<'a>,
709 info: &'a RoomInfo,
710 ) {
711 let width = self.width();
712 let w = width.saturating_sub(2);
713 let shortcodes = self.settings.tunables.message_shortcode_display;
714 let (mut replied, _) = msg.show_msg(w, style, true, shortcodes);
715 let mut sender = msg.sender_span(info, self.settings);
716 let sender_width = UnicodeWidthStr::width(sender.content.as_ref());
717 let trailing = w.saturating_sub(sender_width + 1);
718
719 sender.style = sender.style.patch(style);
720
721 self.push_spans(
722 Line::from(vec![
723 Span::styled(" ", style),
724 Span::styled(THICK_VERTICAL, style),
725 sender,
726 Span::styled(":", style),
727 space_span(trailing, style),
728 ]),
729 style,
730 text,
731 );
732
733 for line in replied.lines.iter_mut() {
734 line.spans.insert(0, Span::styled(THICK_VERTICAL, style));
735 line.spans.insert(0, Span::styled(" ", style));
736 }
737
738 self.push_text(replied, style, text);
739 }
740
741 fn push_reactions(&mut self, counts: Vec<(&'a str, usize)>, style: Style, text: &mut Text<'a>) {
742 let mut emojis = printer::TextPrinter::new(self.width(), style, false, false);
743 let mut reactions = 0;
744
745 for (key, count) in counts {
746 if reactions != 0 {
747 emojis.push_str(" ", style);
748 }
749
750 let name = if self.settings.tunables.reaction_shortcode_display {
751 if let Some(emoji) = emojis::get(key) {
752 if let Some(short) = emoji.shortcode() {
753 short
754 } else {
755 // No ASCII shortcode name to show.
756 continue;
757 }
758 } else if key.chars().all(|c| c.is_ascii_alphanumeric()) {
759 key
760 } else {
761 // Not an Emoji or a printable ASCII string.
762 continue;
763 }
764 } else {
765 key
766 };
767
768 emojis.push_str("[", style);
769 emojis.push_str(name, style);
770 emojis.push_str(" ", style);
771 emojis.push_span_nobreak(Span::styled(count.to_string(), style));
772 emojis.push_str("]", style);
773
774 reactions += 1;
775 }
776
777 if reactions > 0 {
778 self.push_text(emojis.finish(), style, text);
779 }
780 }
781
782 fn push_thread_reply_count(&mut self, len: usize, text: &mut Text<'a>) {
783 if len == 0 {
784 return;
785 }
786
787 // If we have threaded replies to this message, show how many.
788 let plural = len != 1;
789 let style = Style::default();
790 let mut threaded =
791 printer::TextPrinter::new(self.width(), style, false, false).literal(true);
792 let len = Span::styled(len.to_string(), style.add_modifier(StyleModifier::BOLD));
793 threaded.push_str(" \u{2937} ", style);
794 threaded.push_span_nobreak(len);
795 if plural {
796 threaded.push_str(" replies in thread", style);
797 } else {
798 threaded.push_str(" reply in thread", style);
799 }
800
801 self.push_text(threaded.finish(), style, text);
802 }
803}
804
805pub enum ImageStatus {
806 None,
807 Downloading(ImagePreviewSize),
808 Loaded(Box<dyn Protocol>),
809 Error(String),
810}
811
812pub struct Message {
813 pub event: MessageEvent,
814 pub sender: OwnedUserId,
815 pub timestamp: MessageTimeStamp,
816 pub downloaded: bool,
817 pub html: Option<StyleTree>,
818 pub image_preview: ImageStatus,
819}
820
821impl Message {
822 pub fn new(event: MessageEvent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self {
823 let html = event.html();
824 let downloaded = false;
825
826 Message {
827 event,
828 sender,
829 timestamp,
830 downloaded,
831 html,
832 image_preview: ImageStatus::None,
833 }
834 }
835
836 pub fn reply_to(&self) -> Option<OwnedEventId> {
837 let content = match &self.event {
838 MessageEvent::EncryptedOriginal(_) => return None,
839 MessageEvent::EncryptedRedacted(_) => return None,
840 MessageEvent::Local(_, content) => content,
841 MessageEvent::Original(ev) => &ev.content,
842 MessageEvent::Redacted(_) => return None,
843 };
844
845 match &content.relates_to {
846 Some(Relation::Reply { in_reply_to }) => Some(in_reply_to.event_id.clone()),
847 Some(Relation::Thread(Thread {
848 in_reply_to: Some(in_reply_to),
849 is_falling_back: false,
850 ..
851 })) => Some(in_reply_to.event_id.clone()),
852 Some(_) | None => None,
853 }
854 }
855
856 fn thread_root(&self) -> Option<OwnedEventId> {
857 let content = match &self.event {
858 MessageEvent::EncryptedOriginal(_) => return None,
859 MessageEvent::EncryptedRedacted(_) => return None,
860 MessageEvent::Local(_, content) => content,
861 MessageEvent::Original(ev) => &ev.content,
862 MessageEvent::Redacted(_) => return None,
863 };
864
865 match &content.relates_to {
866 Some(Relation::Thread(Thread {
867 event_id,
868 in_reply_to: Some(in_reply_to),
869 is_falling_back: true,
870 ..
871 })) if event_id == &in_reply_to.event_id => Some(event_id.clone()),
872 Some(_) | None => None,
873 }
874 }
875
876 fn get_render_style(&self, selected: bool, settings: &ApplicationSettings) -> Style {
877 let mut style = Style::default();
878
879 if selected {
880 style = style.add_modifier(StyleModifier::REVERSED)
881 }
882
883 if self.timestamp.is_local_echo() {
884 style = style.add_modifier(StyleModifier::ITALIC);
885 }
886
887 if settings.tunables.message_user_color {
888 let color = settings.get_user_color(&self.sender);
889 style = style.fg(color);
890 }
891
892 return style;
893 }
894
895 fn get_render_format<'a>(
896 &'a self,
897 prev: Option<&Message>,
898 width: usize,
899 info: &'a RoomInfo,
900 settings: &'a ApplicationSettings,
901 ) -> MessageFormatter<'a> {
902 let orig = width;
903 let date = match &prev {
904 Some(prev) if prev.timestamp.same_day(&self.timestamp) => None,
905 _ => self.timestamp.show_date(),
906 };
907 let user_gutter = settings.tunables.user_gutter_width;
908
909 if user_gutter + TIME_GUTTER + READ_GUTTER + MIN_MSG_LEN <= width &&
910 settings.tunables.read_receipt_display
911 {
912 let cols = MessageColumns::Four;
913 let fill = width - user_gutter - TIME_GUTTER - READ_GUTTER;
914 let user = self.show_sender(prev, true, info, settings);
915 let time = self.timestamp.show_time();
916 let read = info.event_receipts.get(self.event.event_id()).map(|read| read.iter());
917
918 MessageFormatter { settings, cols, orig, fill, user, date, time, read }
919 } else if user_gutter + TIME_GUTTER + MIN_MSG_LEN <= width {
920 let cols = MessageColumns::Three;
921 let fill = width - user_gutter - TIME_GUTTER;
922 let user = self.show_sender(prev, true, info, settings);
923 let time = self.timestamp.show_time();
924 let read = None;
925
926 MessageFormatter { settings, cols, orig, fill, user, date, time, read }
927 } else if user_gutter + MIN_MSG_LEN <= width {
928 let cols = MessageColumns::Two;
929 let fill = width - user_gutter;
930 let user = self.show_sender(prev, true, info, settings);
931 let time = None;
932 let read = None;
933
934 MessageFormatter { settings, cols, orig, fill, user, date, time, read }
935 } else {
936 let cols = MessageColumns::One;
937 let fill = width.saturating_sub(2);
938 let user = self.show_sender(prev, false, info, settings);
939 let time = None;
940 let read = None;
941
942 MessageFormatter { settings, cols, orig, fill, user, date, time, read }
943 }
944 }
945
946 /// Render the message as a [Text] object for the terminal.
947 ///
948 /// This will also get the image preview Protocol with an x/y offset.
949 pub fn show_with_preview<'a>(
950 &'a self,
951 prev: Option<&Message>,
952 selected: bool,
953 vwctx: &ViewportContext<MessageCursor>,
954 info: &'a RoomInfo,
955 settings: &'a ApplicationSettings,
956 ) -> (Text<'a>, Option<(&dyn Protocol, u16, u16)>) {
957 let width = vwctx.get_width();
958
959 let style = self.get_render_style(selected, settings);
960 let mut fmt = self.get_render_format(prev, width, info, settings);
961 let mut text = Text::default();
962 let width = fmt.width();
963
964 // Show the message that this one replied to, if any.
965 let reply = self
966 .reply_to()
967 .or_else(|| self.thread_root())
968 .and_then(|e| info.get_event(&e));
969
970 if let Some(r) = &reply {
971 fmt.push_in_reply(r, style, &mut text, info);
972 }
973
974 // Now show the message contents, and the inlined reply if we couldn't find it above.
975 let (msg, proto) = self.show_msg(
976 width,
977 style,
978 reply.is_some(),
979 settings.tunables.message_shortcode_display,
980 );
981
982 // Given our text so far, determine the image offset.
983 let proto = proto.map(|p| {
984 let y_off = text.lines.len() as u16;
985 let x_off = fmt.cols.user_gutter_width(settings);
986 // Adjust y_off by 1 if a date was printed before the message to account for the extra line.
987 let y_off = if fmt.date.is_some() { y_off + 1 } else { y_off };
988 (p, x_off, y_off)
989 });
990
991 fmt.push_text(msg, style, &mut text);
992
993 if text.lines.is_empty() {
994 // If there was nothing in the body, just show an empty message.
995 fmt.push_spans(space_span(width, style).into(), style, &mut text);
996 }
997
998 if settings.tunables.reaction_display {
999 let reactions = info.get_reactions(self.event.event_id());
1000 fmt.push_reactions(reactions, style, &mut text);
1001 }
1002
1003 if let Some(thread) = info.get_thread(Some(self.event.event_id())) {
1004 fmt.push_thread_reply_count(thread.len(), &mut text);
1005 }
1006
1007 (text, proto)
1008 }
1009
1010 pub fn show<'a>(
1011 &'a self,
1012 prev: Option<&Message>,
1013 selected: bool,
1014 vwctx: &ViewportContext<MessageCursor>,
1015 info: &'a RoomInfo,
1016 settings: &'a ApplicationSettings,
1017 ) -> Text<'a> {
1018 self.show_with_preview(prev, selected, vwctx, info, settings).0
1019 }
1020
1021 fn show_msg(
1022 &self,
1023 width: usize,
1024 style: Style,
1025 hide_reply: bool,
1026 emoji_shortcodes: bool,
1027 ) -> (Text, Option<&dyn Protocol>) {
1028 if let Some(html) = &self.html {
1029 (html.to_text(width, style, hide_reply, emoji_shortcodes), None)
1030 } else {
1031 let mut msg = self.event.body();
1032 if emoji_shortcodes {
1033 msg = Cow::Owned(replace_emojis_in_str(msg.as_ref()));
1034 }
1035
1036 if self.downloaded {
1037 msg.to_mut().push_str(" \u{2705}");
1038 }
1039
1040 let mut proto = None;
1041 let placeholder = match &self.image_preview {
1042 ImageStatus::None => None,
1043 ImageStatus::Downloading(image_preview_size) => {
1044 placeholder_frame(Some("Downloading..."), width, image_preview_size)
1045 },
1046 ImageStatus::Loaded(backend) => {
1047 proto = Some(backend.as_ref());
1048 placeholder_frame(None, width, &backend.rect().into())
1049 },
1050 ImageStatus::Error(err) => Some(format!("[Image error: {err}]\n")),
1051 };
1052
1053 if let Some(placeholder) = placeholder {
1054 msg.to_mut().insert_str(0, &placeholder);
1055 }
1056
1057 (wrapped_text(msg, width, style), proto)
1058 }
1059 }
1060
1061 fn sender_span<'a>(
1062 &'a self,
1063 info: &'a RoomInfo,
1064 settings: &'a ApplicationSettings,
1065 ) -> Span<'a> {
1066 settings.get_user_span(self.sender.as_ref(), info)
1067 }
1068
1069 fn show_sender<'a>(
1070 &'a self,
1071 prev: Option<&Message>,
1072 align_right: bool,
1073 info: &'a RoomInfo,
1074 settings: &'a ApplicationSettings,
1075 ) -> Option<Span<'a>> {
1076 if let Some(prev) = prev {
1077 if self.sender == prev.sender &&
1078 self.timestamp.same_day(&prev.timestamp) &&
1079 !self.event.is_emote()
1080 {
1081 return None;
1082 }
1083 }
1084
1085 let Span { content, style } = self.sender_span(info, settings);
1086 let user_gutter = settings.tunables.user_gutter_width;
1087 let ((truncated, width), _) = take_width(content, user_gutter - 2);
1088 let padding = user_gutter - 2 - width;
1089
1090 let sender = if align_right {
1091 space(padding) + &truncated + " "
1092 } else {
1093 truncated.into_owned() + &space(padding) + " "
1094 };
1095
1096 Span::styled(sender, style).into()
1097 }
1098
1099 pub fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
1100 self.event.redact(redaction, version);
1101 self.html = None;
1102 }
1103}
1104
1105impl From<RoomEncryptedEvent> for Message {
1106 fn from(event: RoomEncryptedEvent) -> Self {
1107 let timestamp = event.origin_server_ts().into();
1108 let user_id = event.sender().to_owned();
1109 let content = match event {
1110 RoomEncryptedEvent::Original(ev) => MessageEvent::EncryptedOriginal(ev.into()),
1111 RoomEncryptedEvent::Redacted(ev) => MessageEvent::EncryptedRedacted(ev.into()),
1112 };
1113
1114 Message::new(content, user_id, timestamp)
1115 }
1116}
1117
1118impl From<OriginalRoomMessageEvent> for Message {
1119 fn from(event: OriginalRoomMessageEvent) -> Self {
1120 let timestamp = event.origin_server_ts.into();
1121 let user_id = event.sender.clone();
1122 let content = MessageEvent::Original(event.into());
1123
1124 Message::new(content, user_id, timestamp)
1125 }
1126}
1127
1128impl From<RedactedRoomMessageEvent> for Message {
1129 fn from(event: RedactedRoomMessageEvent) -> Self {
1130 let timestamp = event.origin_server_ts.into();
1131 let user_id = event.sender.clone();
1132 let content = MessageEvent::Redacted(event.into());
1133
1134 Message::new(content, user_id, timestamp)
1135 }
1136}
1137
1138impl From<RoomMessageEvent> for Message {
1139 fn from(event: RoomMessageEvent) -> Self {
1140 match event {
1141 RoomMessageEvent::Original(ev) => ev.into(),
1142 RoomMessageEvent::Redacted(ev) => ev.into(),
1143 }
1144 }
1145}
1146
1147impl ToString for Message {
1148 fn to_string(&self) -> String {
1149 self.event.body().into_owned()
1150 }
1151}
1152
1153#[cfg(test)]
1154pub mod tests {
1155 use matrix_sdk::ruma::events::room::{
1156 message::{
1157 AudioInfo,
1158 AudioMessageEventContent,
1159 FileInfo,
1160 FileMessageEventContent,
1161 ImageMessageEventContent,
1162 VideoInfo,
1163 VideoMessageEventContent,
1164 },
1165 ImageInfo,
1166 };
1167
1168 use super::*;
1169 use crate::tests::*;
1170
1171 #[test]
1172 fn test_mc_cmp() {
1173 let mc1 = MessageCursor::from(MSG1_KEY.clone());
1174 let mc2 = MessageCursor::from(MSG2_KEY.clone());
1175 let mc3 = MessageCursor::from(MSG3_KEY.clone());
1176 let mc4 = MessageCursor::from(MSG4_KEY.clone());
1177 let mc5 = MessageCursor::from(MSG5_KEY.clone());
1178
1179 // Everything is equal to itself.
1180 assert_eq!(mc1.cmp(&mc1), Ordering::Equal);
1181 assert_eq!(mc2.cmp(&mc2), Ordering::Equal);
1182 assert_eq!(mc3.cmp(&mc3), Ordering::Equal);
1183 assert_eq!(mc4.cmp(&mc4), Ordering::Equal);
1184 assert_eq!(mc5.cmp(&mc5), Ordering::Equal);
1185
1186 // Local echo is always greater than an origin server timestamp.
1187 assert_eq!(mc1.cmp(&mc2), Ordering::Greater);
1188 assert_eq!(mc1.cmp(&mc3), Ordering::Greater);
1189 assert_eq!(mc1.cmp(&mc4), Ordering::Greater);
1190 assert_eq!(mc1.cmp(&mc5), Ordering::Greater);
1191
1192 // mc2 is the smallest timestamp.
1193 assert_eq!(mc2.cmp(&mc1), Ordering::Less);
1194 assert_eq!(mc2.cmp(&mc3), Ordering::Less);
1195 assert_eq!(mc2.cmp(&mc4), Ordering::Less);
1196 assert_eq!(mc2.cmp(&mc5), Ordering::Less);
1197
1198 // mc3 should be less than mc4 because of its event ID.
1199 assert_eq!(mc3.cmp(&mc1), Ordering::Less);
1200 assert_eq!(mc3.cmp(&mc2), Ordering::Greater);
1201 assert_eq!(mc3.cmp(&mc4), Ordering::Less);
1202 assert_eq!(mc3.cmp(&mc5), Ordering::Less);
1203
1204 // mc4 should be greater than mc3 because of its event ID.
1205 assert_eq!(mc4.cmp(&mc1), Ordering::Less);
1206 assert_eq!(mc4.cmp(&mc2), Ordering::Greater);
1207 assert_eq!(mc4.cmp(&mc3), Ordering::Greater);
1208 assert_eq!(mc4.cmp(&mc5), Ordering::Less);
1209
1210 // mc5 is the greatest OriginServer timestamp.
1211 assert_eq!(mc5.cmp(&mc1), Ordering::Less);
1212 assert_eq!(mc5.cmp(&mc2), Ordering::Greater);
1213 assert_eq!(mc5.cmp(&mc3), Ordering::Greater);
1214 assert_eq!(mc5.cmp(&mc4), Ordering::Greater);
1215 }
1216
1217 #[test]
1218 fn test_mc_to_key() {
1219 let messages = mock_messages();
1220 let mc1 = MessageCursor::from(MSG1_KEY.clone());
1221 let mc2 = MessageCursor::from(MSG2_KEY.clone());
1222 let mc3 = MessageCursor::from(MSG3_KEY.clone());
1223 let mc4 = MessageCursor::from(MSG4_KEY.clone());
1224 let mc5 = MessageCursor::from(MSG5_KEY.clone());
1225 let mc6 = MessageCursor::latest();
1226
1227 let k1 = mc1.to_key(&messages).unwrap();
1228 let k2 = mc2.to_key(&messages).unwrap();
1229 let k3 = mc3.to_key(&messages).unwrap();
1230 let k4 = mc4.to_key(&messages).unwrap();
1231 let k5 = mc5.to_key(&messages).unwrap();
1232 let k6 = mc6.to_key(&messages).unwrap();
1233
1234 // These should all be equal to their MSGN_KEYs.
1235 assert_eq!(k1, &MSG1_KEY.clone());
1236 assert_eq!(k2, &MSG2_KEY.clone());
1237 assert_eq!(k3, &MSG3_KEY.clone());
1238 assert_eq!(k4, &MSG4_KEY.clone());
1239 assert_eq!(k5, &MSG5_KEY.clone());
1240
1241 // MessageCursor::latest() turns into the largest key (our local echo message).
1242 assert_eq!(k6, &MSG1_KEY.clone());
1243
1244 // MessageCursor::latest() fails to convert for a room w/o messages.
1245 let messages_empty = Messages::default();
1246 assert_eq!(mc6.to_key(&messages_empty), None);
1247 }
1248
1249 #[test]
1250 fn test_mc_to_from_cursor() {
1251 let messages = mock_messages();
1252 let mc1 = MessageCursor::from(MSG1_KEY.clone());
1253 let mc2 = MessageCursor::from(MSG2_KEY.clone());
1254 let mc3 = MessageCursor::from(MSG3_KEY.clone());
1255 let mc4 = MessageCursor::from(MSG4_KEY.clone());
1256 let mc5 = MessageCursor::from(MSG5_KEY.clone());
1257 let mc6 = MessageCursor::latest();
1258
1259 let identity = |mc: &MessageCursor| {
1260 let c = mc.to_cursor(&messages).unwrap();
1261
1262 MessageCursor::from_cursor(&c, &messages).unwrap()
1263 };
1264
1265 // These should all convert to a Cursor and back to the original value.
1266 assert_eq!(identity(&mc1), mc1);
1267 assert_eq!(identity(&mc2), mc2);
1268 assert_eq!(identity(&mc3), mc3);
1269 assert_eq!(identity(&mc4), mc4);
1270 assert_eq!(identity(&mc5), mc5);
1271
1272 // MessageCursor::latest() should point at the most recent message after conversion.
1273 assert_eq!(identity(&mc6), mc1);
1274 }
1275
1276 #[test]
1277 fn test_markdown_autolink() {
1278 let input = "http://example.com\n";
1279 let content = text_to_message_content(input.into());
1280 assert_eq!(content.body, input);
1281 assert_eq!(
1282 content.formatted.unwrap().body,
1283 "<p><a href=\"http://example.com\">http://example.com</a></p>\n"
1284 );
1285
1286 let input = "www.example.com\n";
1287 let content = text_to_message_content(input.into());
1288 assert_eq!(content.body, input);
1289 assert_eq!(
1290 content.formatted.unwrap().body,
1291 "<p><a href=\"http://www.example.com\">www.example.com</a></p>\n"
1292 );
1293
1294 let input = "See docs (they're at https://iamb.chat)\n";
1295 let content = text_to_message_content(input.into());
1296 assert_eq!(content.body, input);
1297 assert_eq!(
1298 content.formatted.unwrap().body,
1299 "<p>See docs (they're at <a href=\"https://iamb.chat\">https://iamb.chat</a>)</p>\n"
1300 );
1301 }
1302
1303 #[test]
1304 fn test_markdown_message() {
1305 let input = "**bold**\n";
1306 let content = text_to_message_content(input.into());
1307 assert_eq!(content.body, input);
1308 assert_eq!(content.formatted.unwrap().body, "<p><strong>bold</strong></p>\n");
1309
1310 let input = "*emphasis*\n";
1311 let content = text_to_message_content(input.into());
1312 assert_eq!(content.body, input);
1313 assert_eq!(content.formatted.unwrap().body, "<p><em>emphasis</em></p>\n");
1314
1315 let input = "`code`\n";
1316 let content = text_to_message_content(input.into());
1317 assert_eq!(content.body, input);
1318 assert_eq!(content.formatted.unwrap().body, "<p><code>code</code></p>\n");
1319
1320 let input = "```rust\nconst A: usize = 1;\n```\n";
1321 let content = text_to_message_content(input.into());
1322 assert_eq!(content.body, input);
1323 assert_eq!(
1324 content.formatted.unwrap().body,
1325 "<pre><code class=\"language-rust\">const A: usize = 1;\n</code></pre>\n"
1326 );
1327
1328 let input = ":heart:\n";
1329 let content = text_to_message_content(input.into());
1330 assert_eq!(content.body, input);
1331 assert_eq!(content.formatted.unwrap().body, "<p>\u{2764}\u{FE0F}</p>\n");
1332
1333 let input = "para 1\n\npara 2\n";
1334 let content = text_to_message_content(input.into());
1335 assert_eq!(content.body, input);
1336 assert_eq!(content.formatted.unwrap().body, "<p>para 1</p>\n<p>para 2</p>\n");
1337
1338 let input = "line 1\nline 2\n";
1339 let content = text_to_message_content(input.into());
1340 assert_eq!(content.body, input);
1341 assert_eq!(content.formatted.unwrap().body, "<p>line 1<br />\nline 2</p>\n");
1342
1343 let input = "# Heading\n## Subheading\n\ntext\n";
1344 let content = text_to_message_content(input.into());
1345 assert_eq!(content.body, input);
1346 assert_eq!(
1347 content.formatted.unwrap().body,
1348 "<h1>Heading</h1>\n<h2>Subheading</h2>\n<p>text</p>\n"
1349 );
1350 }
1351
1352 #[test]
1353 fn test_placeholder_frame() {
1354 fn pretty_frame_test(str: &str) -> Option<String> {
1355 Some(str[1..].to_string())
1356 }
1357
1358 assert_eq!(
1359 placeholder_frame(None, 4, &ImagePreviewSize { width: 4, height: 4 }),
1360 pretty_frame_test(
1361 r#"
1362⌌ ⌍
1363
1364
1365⌎ ⌏
1366"#
1367 )
1368 );
1369
1370 assert_eq!(placeholder_frame(None, 2, &ImagePreviewSize { width: 4, height: 4 }), None);
1371 assert_eq!(placeholder_frame(None, 4, &ImagePreviewSize { width: 1, height: 4 }), None);
1372
1373 assert_eq!(placeholder_frame(None, 4, &ImagePreviewSize { width: 4, height: 1 }), None);
1374
1375 assert_eq!(
1376 placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 4, height: 4 }),
1377 pretty_frame_test(
1378 r#"
1379⌌ ⌍
1380 OK
1381
1382⌎ ⌏
1383"#
1384 )
1385 );
1386 assert_eq!(
1387 placeholder_frame(Some("idontfit"), 4, &ImagePreviewSize { width: 4, height: 4 }),
1388 pretty_frame_test(
1389 r#"
1390⌌ ⌍
1391
1392
1393⌎ ⌏
1394"#
1395 )
1396 );
1397 assert_eq!(
1398 placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 4, height: 2 }),
1399 pretty_frame_test(
1400 r#"
1401⌌ ⌍
1402⌎ ⌏
1403"#
1404 )
1405 );
1406 assert_eq!(
1407 placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 2, height: 3 }),
1408 pretty_frame_test(
1409 r#"
1410⌌⌍
1411
1412⌎⌏
1413"#
1414 )
1415 );
1416 }
1417
1418 #[test]
1419 fn test_display_attachment_size() {
1420 assert_eq!(
1421 body_cow_content(&RoomMessageEventContent::new(MessageType::Image(
1422 ImageMessageEventContent::plain(
1423 "Alt text".to_string(),
1424 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1425 )
1426 .info(Some(Box::new(ImageInfo::default())))
1427 ))),
1428 "[Attached Image: Alt text]".to_string()
1429 );
1430
1431 let mut info = ImageInfo::default();
1432 info.size = Some(442630_u32.into());
1433 assert_eq!(
1434 body_cow_content(&RoomMessageEventContent::new(MessageType::Image(
1435 ImageMessageEventContent::plain(
1436 "Alt text".to_string(),
1437 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1438 )
1439 .info(Some(Box::new(info)))
1440 ))),
1441 "[Attached Image: Alt text (442.63 kB)]".to_string()
1442 );
1443
1444 let mut info = ImageInfo::default();
1445 info.size = Some(12_u32.into());
1446 assert_eq!(
1447 body_cow_content(&RoomMessageEventContent::new(MessageType::Image(
1448 ImageMessageEventContent::plain(
1449 "Alt text".to_string(),
1450 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1451 )
1452 .info(Some(Box::new(info)))
1453 ))),
1454 "[Attached Image: Alt text (12 B)]".to_string()
1455 );
1456
1457 let mut info = AudioInfo::default();
1458 info.size = Some(4294967295_u32.into());
1459 assert_eq!(
1460 body_cow_content(&RoomMessageEventContent::new(MessageType::Audio(
1461 AudioMessageEventContent::plain(
1462 "Alt text".to_string(),
1463 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1464 )
1465 .info(Some(Box::new(info)))
1466 ))),
1467 "[Attached Audio: Alt text (4.29 GB)]".to_string()
1468 );
1469
1470 let mut info = FileInfo::default();
1471 info.size = Some(4426300_u32.into());
1472 assert_eq!(
1473 body_cow_content(&RoomMessageEventContent::new(MessageType::File(
1474 FileMessageEventContent::plain(
1475 "Alt text".to_string(),
1476 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1477 )
1478 .info(Some(Box::new(info)))
1479 ))),
1480 "[Attached File: Alt text (4.43 MB)]".to_string()
1481 );
1482
1483 let mut info = VideoInfo::default();
1484 info.size = Some(44000_u32.into());
1485 assert_eq!(
1486 body_cow_content(&RoomMessageEventContent::new(MessageType::Video(
1487 VideoMessageEventContent::plain(
1488 "Alt text".to_string(),
1489 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1490 )
1491 .info(Some(Box::new(info)))
1492 ))),
1493 "[Attached Video: Alt text (44 kB)]".to_string()
1494 );
1495 }
1496}