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