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