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