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