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