src/message/mod.rs
1778 lines · 56853 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::layout::Size;
21use ratatui::style::Color;
22use ratatui_image::sliced::SlicedProtocol;
23use unicode_width::UnicodeWidthStr;
24
25use matrix_sdk::ruma::{
26 EventId,
27 MilliSecondsSinceUnixEpoch,
28 OwnedEventId,
29 OwnedUserId,
30 UInt,
31 events::{
32 AnySyncStateEvent,
33 RedactedUnsigned,
34 relation::Thread,
35 room::{
36 encrypted::{
37 OriginalRoomEncryptedEvent,
38 RedactedRoomEncryptedEvent,
39 RoomEncryptedEvent,
40 },
41 message::{
42 FormattedBody,
43 MessageFormat,
44 MessageType,
45 OriginalRoomMessageEvent,
46 RedactedRoomMessageEvent,
47 Relation,
48 RoomMessageEvent,
49 RoomMessageEventContent,
50 },
51 redaction::SyncRoomRedactionEvent,
52 },
53 },
54};
55
56use ratatui::{
57 style::{Modifier as StyleModifier, Style},
58 symbols::line::THICK_VERTICAL,
59 text::{Line, Span, Text},
60};
61
62use modalkit::editing::cursor::Cursor;
63use modalkit::prelude::*;
64
65use crate::base::MessageEdits;
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 SlicedProtocol, 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: &Size,
188) -> Option<String> {
189 let Size { width, height } = image_preview_size;
190 let width = usize::min(*width as usize, 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 as usize - 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 as usize / 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) -> Span<'static> {
262 let time = self.as_datetime().format("%A, %B %d %Y").to_string();
263
264 Span::styled(time, BOLD_STYLE)
265 }
266
267 fn show_time(self) -> Span<'static> {
268 let time = self.as_datetime().format("%T");
269 let time = format!(" [{time}]");
270
271 Span::raw(time)
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 pub fn show_date(&self, prev: Option<&Message>) -> bool {
1052 let Some(prev) = prev else { return true };
1053
1054 !prev.timestamp.same_day(self.timestamp)
1055 }
1056 pub fn message_column_width(
1057 viewctx: &ViewportContext<MessageCursor>,
1058 settings: &ApplicationSettings,
1059 ) -> usize {
1060 let width = viewctx.get_width();
1061 let user_gutter = settings.tunables.user_gutter_width;
1062
1063 if user_gutter + TIME_GUTTER + READ_GUTTER + MIN_MSG_LEN <= width &&
1064 settings.tunables.read_receipt_display
1065 {
1066 width - user_gutter - TIME_GUTTER - READ_GUTTER
1067 } else if user_gutter + TIME_GUTTER + MIN_MSG_LEN <= width {
1068 width - user_gutter - TIME_GUTTER
1069 } else if user_gutter + MIN_MSG_LEN <= width {
1070 width - user_gutter
1071 } else {
1072 width.saturating_sub(2)
1073 }
1074 }
1075
1076 fn get_render_format<'a>(
1077 &'a self,
1078 prev: Option<&Message>,
1079 width: usize,
1080 info: &'a RoomInfo,
1081 settings: &'a ApplicationSettings,
1082 ) -> MessageFormatter<'a> {
1083 let orig = width;
1084 let date = self.show_date(prev).then(|| self.timestamp.show_date());
1085 let user_gutter = settings.tunables.user_gutter_width;
1086
1087 if user_gutter + TIME_GUTTER + READ_GUTTER + MIN_MSG_LEN <= width &&
1088 settings.tunables.read_receipt_display
1089 {
1090 let cols = MessageColumns::Four;
1091 let fill = width - user_gutter - TIME_GUTTER - READ_GUTTER;
1092 let user = self.show_sender(prev, true, info, settings, width);
1093 let time = Some(self.timestamp.show_time());
1094 let read = info
1095 .event_receipts
1096 .values()
1097 .filter_map(|receipts| self.event.event_id().and_then(|id| receipts.get(id)))
1098 .flat_map(|read| read.iter())
1099 .map(|user_id| user_id.to_owned())
1100 .collect();
1101
1102 MessageFormatter { settings, cols, orig, fill, user, date, time, read }
1103 } else if user_gutter + TIME_GUTTER + MIN_MSG_LEN <= width {
1104 let cols = MessageColumns::Three;
1105 let fill = width - user_gutter - TIME_GUTTER;
1106 let user = self.show_sender(prev, true, info, settings, width);
1107 let time = Some(self.timestamp.show_time());
1108 let read = Vec::new();
1109
1110 MessageFormatter { settings, cols, orig, fill, user, date, time, read }
1111 } else if user_gutter + MIN_MSG_LEN <= width {
1112 let cols = MessageColumns::Two;
1113 let fill = width - user_gutter;
1114 let user = self.show_sender(prev, true, info, settings, width);
1115 let time = None;
1116 let read = Vec::new();
1117
1118 MessageFormatter { settings, cols, orig, fill, user, date, time, read }
1119 } else {
1120 let cols = MessageColumns::One;
1121 let fill = width.saturating_sub(2);
1122 let user = self.show_sender(prev, false, info, settings, width);
1123 let time = None;
1124 let read = Vec::new();
1125
1126 MessageFormatter { settings, cols, orig, fill, user, date, time, read }
1127 }
1128 }
1129
1130 /// Render the message as a [Text] object for the terminal.
1131 ///
1132 /// This will also get the image preview Protocol with an x/y offset.
1133 pub fn show_with_preview<'a>(
1134 &'a self,
1135 prev: Option<&Message>,
1136 selected: bool,
1137 vwctx: &ViewportContext<MessageCursor>,
1138 info: &'a RoomInfo,
1139 settings: &'a ApplicationSettings,
1140 previews: &'a PreviewManager,
1141 ) -> (Text<'a>, Vec<ProtocolPreview<'a>>) {
1142 let width = vwctx.get_width();
1143
1144 let style = self.get_render_style(selected, settings);
1145 let mut fmt = self.get_render_format(prev, width, info, settings);
1146 let mut text = Text::default();
1147 let width = fmt.width();
1148
1149 let mut protos = Vec::new();
1150
1151 // Show the message that this one replied to, if any.
1152 let reply = self.reply_to().or_else(|| self.thread_root()).map(|e| info.get_event(&e));
1153 if let Some(r) = reply {
1154 if let Some(r) = r {
1155 // Format the reply header, push it into the `Text` buffer, and get any image.
1156 let proto_reply = fmt.push_in_reply(r, style, &mut text, info, settings, previews);
1157 if let Some(proto) = proto_reply {
1158 protos.push(proto)
1159 }
1160 } else {
1161 fmt.push_spans(
1162 Line::from(vec![
1163 Span::styled(" ", style),
1164 Span::styled(THICK_VERTICAL, style),
1165 Span::styled("Original message not loaded", style),
1166 space_span(width.saturating_sub(29), style),
1167 ]),
1168 style,
1169 &mut text,
1170 );
1171 }
1172 }
1173
1174 // Now show the message contents, and the inlined reply if we couldn't find it above.
1175 let (msg, proto) = self.show_msg(width, style, settings, previews);
1176
1177 // Given our text so far, determine the image offset.
1178 if let Some(p) = proto {
1179 let y_off = text.lines.len() as u16;
1180 let x_off = fmt.cols.user_gutter_width(settings);
1181
1182 // Account for extra lines printed before the message;
1183 let y_off = y_off + fmt.message_start_line();
1184 protos.push((p, x_off, y_off));
1185 }
1186
1187 fmt.push_text(msg, style, &mut text);
1188
1189 if text.lines.is_empty() {
1190 // If there was nothing in the body, just show an empty message.
1191 fmt.push_spans(space_span(width, style).into(), style, &mut text);
1192 }
1193
1194 if self.event.is_edited() {
1195 fmt.push_spans(
1196 Line::from(vec![
1197 Span::styled("(edited)", style.fg(Color::Gray)),
1198 space_span(fmt.width().saturating_sub(8), style),
1199 ]),
1200 style,
1201 &mut text,
1202 );
1203 }
1204
1205 if settings.tunables.reaction_display {
1206 let reactions =
1207 self.event.event_id().map(|id| info.get_reactions(id)).unwrap_or_default();
1208 let react_protos = fmt.push_reactions(reactions, style, &mut text, settings, previews);
1209 protos.extend(react_protos);
1210 }
1211
1212 if let Some(thread) = self.event.event_id().and_then(|id| info.get_thread(Some(id))) {
1213 fmt.push_thread_reply_count(thread.len(), &mut text);
1214 }
1215
1216 (text, protos)
1217 }
1218
1219 pub fn show<'a>(
1220 &'a self,
1221 prev: Option<&Message>,
1222 selected: bool,
1223 vwctx: &ViewportContext<MessageCursor>,
1224 info: &'a RoomInfo,
1225 settings: &'a ApplicationSettings,
1226 previews: &'a PreviewManager,
1227 ) -> Text<'a> {
1228 self.show_with_preview(prev, selected, vwctx, info, settings, previews).0
1229 }
1230
1231 fn show_msg<'a>(
1232 &'a self,
1233 width: usize,
1234 style: Style,
1235 settings: &'a ApplicationSettings,
1236 previews: &'a PreviewManager,
1237 ) -> (Text<'a>, Option<&'a SlicedProtocol>) {
1238 let mut proto = None;
1239 let placeholder = match self
1240 .image_preview()
1241 .and_then(|source| previews.get(source, PreviewKind::Message))
1242 {
1243 None => None,
1244 Some(ImageStatus::Queued(image_preview_size)) => {
1245 placeholder_frame(Some("Queued..."), width, image_preview_size)
1246 },
1247 Some(ImageStatus::Downloading(image_preview_size)) => {
1248 placeholder_frame(Some("Downloading..."), width, image_preview_size)
1249 },
1250 Some(ImageStatus::Loaded(backend)) => {
1251 proto = Some(backend);
1252 placeholder_frame(None, width, &backend.size())
1253 },
1254 Some(ImageStatus::Error(err)) => Some(format!("[Image error: {err}]\n")),
1255 };
1256
1257 let mut text = if let Some(placeholder) = placeholder {
1258 wrapped_text(placeholder, width, style)
1259 } else {
1260 Default::default()
1261 };
1262
1263 if let Some(mut filename) = self.event.filename() {
1264 if self.downloaded {
1265 filename.push_str(" \u{2705}");
1266 }
1267
1268 text += wrapped_text(filename, width, style);
1269 }
1270
1271 if let Some(html) = &self.html {
1272 text += html.to_text(width, style, settings);
1273 } else {
1274 let mut msg = self.event.body();
1275 if settings.tunables.message_shortcode_display {
1276 msg = Cow::Owned(replace_emojis_in_str(msg.as_ref()));
1277 }
1278 text += wrapped_text(msg, width, style);
1279 };
1280
1281 (text, proto)
1282 }
1283
1284 fn sender_span<'a>(
1285 &'a self,
1286 info: &'a RoomInfo,
1287 settings: &'a ApplicationSettings,
1288 ) -> Span<'a> {
1289 settings.get_user_span(self.sender.as_ref(), info)
1290 }
1291
1292 fn show_sender<'a>(
1293 &'a self,
1294 prev: Option<&Message>,
1295 gutter_enabled: bool,
1296 info: &'a RoomInfo,
1297 settings: &'a ApplicationSettings,
1298 width: usize,
1299 ) -> SenderSpan<'a> {
1300 if let Some(prev) = prev &&
1301 self.sender == prev.sender &&
1302 self.timestamp.same_day(prev.timestamp) &&
1303 !matches!(self.event.msgtype(), Some(MessageType::Emote(_)))
1304 {
1305 return SenderSpan::None;
1306 }
1307
1308 let Span { content, style } = self.sender_span(info, settings);
1309 let user_gutter = settings.tunables.user_gutter_width;
1310
1311 let show_in_gutter = gutter_enabled && user_gutter > 2;
1312
1313 if show_in_gutter {
1314 let ((truncated, width), _) = take_width(content, user_gutter - 2);
1315 let padding = user_gutter - 2 - width;
1316
1317 let sender = format!("{}{} ", space(padding), truncated);
1318
1319 SenderSpan::Gutter(Span::styled(sender, style))
1320 } else if UnicodeWidthStr::width(content.as_ref()) > width {
1321 let ((truncated, _), _) = take_width(content, width);
1322
1323 SenderSpan::Line(Span::styled(truncated, style))
1324 } else {
1325 SenderSpan::Line(Span::styled(content, style))
1326 }
1327 }
1328
1329 pub fn redact(&mut self, redaction: SyncRoomRedactionEvent) {
1330 self.event.redact(redaction);
1331 self.html = None;
1332 self.downloaded = false;
1333 }
1334
1335 pub fn set_edits(&mut self, new_edits: MessageEdits) {
1336 if let MessageEvent::Original(orig, edits) = &mut self.event {
1337 *edits = new_edits;
1338
1339 for edit in edits.values_mut() {
1340 strip_reply_fallback(&mut edit.msgtype);
1341 }
1342
1343 if let Some(most_recent) = edits.last_key_value() {
1344 self.html = content_html(&most_recent.1.msgtype);
1345 } else {
1346 self.html = content_html(&orig.content.msgtype);
1347 }
1348 }
1349 }
1350
1351 pub fn insert_edit(
1352 &mut self,
1353 key: MessageKey,
1354 mut edit: RoomMessageEventContentWithoutRelation,
1355 ) {
1356 if let MessageEvent::Original(_, edits) = &mut self.event {
1357 strip_reply_fallback(&mut edit.msgtype);
1358
1359 let inserted = edits.entry(key).insert_entry(edit);
1360 self.html = content_html(&inserted.get().msgtype);
1361 }
1362 }
1363
1364 pub fn remove_edit(&mut self, key: &MessageKey) {
1365 let MessageEvent::Original(orig_content, edits) = &mut self.event else {
1366 return;
1367 };
1368
1369 edits.remove(key);
1370
1371 let content = edits
1372 .last_key_value()
1373 .map(|(_, msg)| &msg.msgtype)
1374 .unwrap_or(&orig_content.content.msgtype);
1375
1376 self.html = content_html(content);
1377 }
1378}
1379
1380impl From<RoomEncryptedEvent> for Message {
1381 fn from(event: RoomEncryptedEvent) -> Self {
1382 let timestamp = event.origin_server_ts().into();
1383 let user_id = event.sender().to_owned();
1384 let content = match event {
1385 RoomEncryptedEvent::Original(ev) => MessageEvent::EncryptedOriginal(ev.into()),
1386 RoomEncryptedEvent::Redacted(ev) => MessageEvent::EncryptedRedacted(ev.into()),
1387 };
1388
1389 Message::new(content, user_id, timestamp)
1390 }
1391}
1392
1393impl From<OriginalRoomMessageEvent> for Message {
1394 fn from(event: OriginalRoomMessageEvent) -> Self {
1395 let timestamp = event.origin_server_ts.into();
1396 let user_id = event.sender.clone();
1397 let content = MessageEvent::Original(event.into(), Default::default());
1398
1399 Message::new(content, user_id, timestamp)
1400 }
1401}
1402
1403impl From<RedactedRoomMessageEvent> for Message {
1404 fn from(event: RedactedRoomMessageEvent) -> Self {
1405 let timestamp = event.origin_server_ts.into();
1406 let user_id = event.sender.clone();
1407
1408 let event_id = event.event_id;
1409 let reason = redaction_reason_unsigned(&event.unsigned);
1410 let content = MessageEvent::Redacted(event_id, reason);
1411
1412 Message::new(content, user_id, timestamp)
1413 }
1414}
1415
1416impl From<RoomMessageEvent> for Message {
1417 fn from(event: RoomMessageEvent) -> Self {
1418 match event {
1419 RoomMessageEvent::Original(ev) => ev.into(),
1420 RoomMessageEvent::Redacted(ev) => ev.into(),
1421 }
1422 }
1423}
1424
1425impl From<AnySyncStateEvent> for Message {
1426 fn from(event: AnySyncStateEvent) -> Self {
1427 let timestamp = event.origin_server_ts().into();
1428 let user_id = event.sender().to_owned();
1429 let event = MessageEvent::State(event.into());
1430
1431 Message::new(event, user_id, timestamp)
1432 }
1433}
1434
1435impl From<OriginalStickerEvent> for Message {
1436 fn from(event: OriginalStickerEvent) -> Self {
1437 let timestamp = event.origin_server_ts.into();
1438 let user_id = event.sender.clone();
1439 let source = event.content.source.clone().into();
1440 let content = MessageEvent::Sticker(event.into(), source);
1441
1442 Message::new(content, user_id, timestamp)
1443 }
1444}
1445
1446impl From<RedactedStickerEvent> for Message {
1447 fn from(event: RedactedStickerEvent) -> Self {
1448 let timestamp = event.origin_server_ts.into();
1449 let user_id = event.sender.clone();
1450
1451 let event_id = event.event_id;
1452 let reason = redaction_reason_unsigned(&event.unsigned);
1453 let content = MessageEvent::Redacted(event_id, reason);
1454
1455 Message::new(content, user_id, timestamp)
1456 }
1457}
1458
1459impl From<StickerEvent> for Message {
1460 fn from(event: StickerEvent) -> Self {
1461 match event {
1462 MessageLikeEvent::Original(ev) => ev.into(),
1463 MessageLikeEvent::Redacted(ev) => ev.into(),
1464 }
1465 }
1466}
1467
1468impl Display for Message {
1469 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1470 write!(f, "{}", self.event.body())
1471 }
1472}
1473
1474#[cfg(test)]
1475pub mod tests {
1476 use matrix_sdk::ruma::events::room::{
1477 ImageInfo,
1478 message::{
1479 AudioInfo,
1480 AudioMessageEventContent,
1481 FileInfo,
1482 FileMessageEventContent,
1483 ImageMessageEventContent,
1484 VideoInfo,
1485 VideoMessageEventContent,
1486 },
1487 };
1488
1489 use super::*;
1490 use crate::tests::*;
1491
1492 #[test]
1493 fn test_mc_cmp() {
1494 let mc1 = MessageCursor::from(MSG1_KEY.clone());
1495 let mc2 = MessageCursor::from(MSG2_KEY.clone());
1496 let mc3 = MessageCursor::from(MSG3_KEY.clone());
1497 let mc4 = MessageCursor::from(MSG4_KEY.clone());
1498 let mc5 = MessageCursor::from(MSG5_KEY.clone());
1499
1500 // Everything is equal to itself.
1501 assert_eq!(mc1.cmp(&mc1), Ordering::Equal);
1502 assert_eq!(mc2.cmp(&mc2), Ordering::Equal);
1503 assert_eq!(mc3.cmp(&mc3), Ordering::Equal);
1504 assert_eq!(mc4.cmp(&mc4), Ordering::Equal);
1505 assert_eq!(mc5.cmp(&mc5), Ordering::Equal);
1506
1507 // Local echo is always greater than an origin server timestamp.
1508 assert_eq!(mc1.cmp(&mc2), Ordering::Greater);
1509 assert_eq!(mc1.cmp(&mc3), Ordering::Greater);
1510 assert_eq!(mc1.cmp(&mc4), Ordering::Greater);
1511 assert_eq!(mc1.cmp(&mc5), Ordering::Greater);
1512
1513 // mc2 is the smallest timestamp.
1514 assert_eq!(mc2.cmp(&mc1), Ordering::Less);
1515 assert_eq!(mc2.cmp(&mc3), Ordering::Less);
1516 assert_eq!(mc2.cmp(&mc4), Ordering::Less);
1517 assert_eq!(mc2.cmp(&mc5), Ordering::Less);
1518
1519 // mc3 should be less than mc4 because of its event ID.
1520 assert_eq!(mc3.cmp(&mc1), Ordering::Less);
1521 assert_eq!(mc3.cmp(&mc2), Ordering::Greater);
1522 assert_eq!(mc3.cmp(&mc4), Ordering::Less);
1523 assert_eq!(mc3.cmp(&mc5), Ordering::Less);
1524
1525 // mc4 should be greater than mc3 because of its event ID.
1526 assert_eq!(mc4.cmp(&mc1), Ordering::Less);
1527 assert_eq!(mc4.cmp(&mc2), Ordering::Greater);
1528 assert_eq!(mc4.cmp(&mc3), Ordering::Greater);
1529 assert_eq!(mc4.cmp(&mc5), Ordering::Less);
1530
1531 // mc5 is the greatest OriginServer timestamp.
1532 assert_eq!(mc5.cmp(&mc1), Ordering::Less);
1533 assert_eq!(mc5.cmp(&mc2), Ordering::Greater);
1534 assert_eq!(mc5.cmp(&mc3), Ordering::Greater);
1535 assert_eq!(mc5.cmp(&mc4), Ordering::Greater);
1536 }
1537
1538 #[test]
1539 fn test_mc_to_key() {
1540 let messages = mock_messages();
1541 let mc1 = MessageCursor::from(MSG1_KEY.clone());
1542 let mc2 = MessageCursor::from(MSG2_KEY.clone());
1543 let mc3 = MessageCursor::from(MSG3_KEY.clone());
1544 let mc4 = MessageCursor::from(MSG4_KEY.clone());
1545 let mc5 = MessageCursor::from(MSG5_KEY.clone());
1546 let mc6 = MessageCursor::latest();
1547
1548 let k1 = mc1.to_key(&messages).unwrap();
1549 let k2 = mc2.to_key(&messages).unwrap();
1550 let k3 = mc3.to_key(&messages).unwrap();
1551 let k4 = mc4.to_key(&messages).unwrap();
1552 let k5 = mc5.to_key(&messages).unwrap();
1553 let k6 = mc6.to_key(&messages).unwrap();
1554
1555 // These should all be equal to their MSGN_KEYs.
1556 assert_eq!(k1, &MSG1_KEY.clone());
1557 assert_eq!(k2, &MSG2_KEY.clone());
1558 assert_eq!(k3, &MSG3_KEY.clone());
1559 assert_eq!(k4, &MSG4_KEY.clone());
1560 assert_eq!(k5, &MSG5_KEY.clone());
1561
1562 // MessageCursor::latest() turns into the largest key (our local echo message).
1563 assert_eq!(k6, &MSG1_KEY.clone());
1564
1565 // MessageCursor::latest() fails to convert for a room w/o messages.
1566 let messages_empty = Messages::new(ReceiptThread::Main);
1567 assert_eq!(mc6.to_key(&messages_empty), None);
1568 }
1569
1570 #[test]
1571 fn test_mc_to_from_cursor() {
1572 let messages = mock_messages();
1573 let mc1 = MessageCursor::from(MSG1_KEY.clone());
1574 let mc2 = MessageCursor::from(MSG2_KEY.clone());
1575 let mc3 = MessageCursor::from(MSG3_KEY.clone());
1576 let mc4 = MessageCursor::from(MSG4_KEY.clone());
1577 let mc5 = MessageCursor::from(MSG5_KEY.clone());
1578 let mc6 = MessageCursor::latest();
1579
1580 let identity = |mc: &MessageCursor| {
1581 let c = mc.to_cursor(&messages).unwrap();
1582
1583 MessageCursor::from_cursor(&c, &messages).unwrap()
1584 };
1585
1586 // These should all convert to a Cursor and back to the original value.
1587 assert_eq!(identity(&mc1), mc1);
1588 assert_eq!(identity(&mc2), mc2);
1589 assert_eq!(identity(&mc3), mc3);
1590 assert_eq!(identity(&mc4), mc4);
1591 assert_eq!(identity(&mc5), mc5);
1592
1593 // MessageCursor::latest() should point at the most recent message after conversion.
1594 assert_eq!(identity(&mc6), mc1);
1595 }
1596
1597 #[test]
1598 fn test_placeholder_frame() {
1599 fn pretty_frame_test(str: &str) -> Option<String> {
1600 Some(str[1..].to_string())
1601 }
1602
1603 assert_eq!(
1604 placeholder_frame(None, 4, &Size { width: 4, height: 4 }),
1605 pretty_frame_test(
1606 r#"
1607⌌ ⌍
1608
1609
1610⌎ ⌏
1611"#
1612 )
1613 );
1614
1615 assert_eq!(
1616 placeholder_frame(None, 2, &Size { width: 4, height: 4 }),
1617 pretty_frame_test(
1618 r#"
1619⌌⌍
1620
1621
1622⌎⌏
1623"#
1624 )
1625 );
1626 assert_eq!(placeholder_frame(None, 4, &Size { width: 1, height: 4 }), None);
1627
1628 assert_eq!(placeholder_frame(None, 4, &Size { width: 4, height: 1 }), None);
1629
1630 assert_eq!(
1631 placeholder_frame(Some("OK"), 4, &Size { width: 4, height: 4 }),
1632 pretty_frame_test(
1633 r#"
1634⌌ ⌍
1635 OK
1636
1637⌎ ⌏
1638"#
1639 )
1640 );
1641 assert_eq!(
1642 placeholder_frame(Some("OK"), 6, &Size { width: 6, height: 6 }),
1643 pretty_frame_test(
1644 r#"
1645⌌ ⌍
1646
1647 OK
1648
1649
1650⌎ ⌏
1651"#
1652 )
1653 );
1654 assert_eq!(
1655 placeholder_frame(Some("OK"), 6, &Size { width: 6, height: 7 }),
1656 pretty_frame_test(
1657 r#"
1658⌌ ⌍
1659
1660
1661 OK
1662
1663
1664⌎ ⌏
1665"#
1666 )
1667 );
1668 assert_eq!(
1669 placeholder_frame(Some("idontfit"), 4, &Size { width: 4, height: 4 }),
1670 pretty_frame_test(
1671 r#"
1672⌌ ⌍
1673
1674
1675⌎ ⌏
1676"#
1677 )
1678 );
1679 assert_eq!(
1680 placeholder_frame(Some("OK"), 4, &Size { width: 4, height: 2 }),
1681 pretty_frame_test(
1682 r#"
1683⌌ ⌍
1684⌎ ⌏
1685"#
1686 )
1687 );
1688 assert_eq!(
1689 placeholder_frame(Some("OK"), 4, &Size { width: 2, height: 3 }),
1690 pretty_frame_test(
1691 r#"
1692⌌⌍
1693
1694⌎⌏
1695"#
1696 )
1697 );
1698 }
1699
1700 #[test]
1701 fn test_display_attachment_size() {
1702 assert_eq!(
1703 content_filename(&MessageType::Image(
1704 ImageMessageEventContent::plain(
1705 "Alt text".to_string(),
1706 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1707 )
1708 .info(Some(Box::default()))
1709 )),
1710 "[Attached Image: Alt text]".to_string().into()
1711 );
1712
1713 let mut info = ImageInfo::default();
1714 info.size = Some(442630_u32.into());
1715 assert_eq!(
1716 content_filename(&MessageType::Image(
1717 ImageMessageEventContent::plain(
1718 "Alt text".to_string(),
1719 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1720 )
1721 .info(Some(Box::new(info)))
1722 )),
1723 "[Attached Image: Alt text (442.63 kB)]".to_string().into()
1724 );
1725
1726 let mut info = ImageInfo::default();
1727 info.size = Some(12_u32.into());
1728 assert_eq!(
1729 content_filename(&MessageType::Image(
1730 ImageMessageEventContent::plain(
1731 "Alt text".to_string(),
1732 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1733 )
1734 .info(Some(Box::new(info)))
1735 )),
1736 "[Attached Image: Alt text (12 B)]".to_string().into()
1737 );
1738
1739 let mut info = AudioInfo::default();
1740 info.size = Some(4294967295_u32.into());
1741 assert_eq!(
1742 content_filename(&MessageType::Audio(
1743 AudioMessageEventContent::plain(
1744 "Alt text".to_string(),
1745 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1746 )
1747 .info(Some(Box::new(info)))
1748 )),
1749 "[Attached Audio: Alt text (4.29 GB)]".to_string().into()
1750 );
1751
1752 let mut info = FileInfo::default();
1753 info.size = Some(4426300_u32.into());
1754 assert_eq!(
1755 content_filename(&MessageType::File(
1756 FileMessageEventContent::plain(
1757 "Alt text".to_string(),
1758 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1759 )
1760 .info(Some(Box::new(info)))
1761 )),
1762 "[Attached File: Alt text (4.43 MB)]".to_string().into()
1763 );
1764
1765 let mut info = VideoInfo::default();
1766 info.size = Some(44000_u32.into());
1767 assert_eq!(
1768 content_filename(&MessageType::Video(
1769 VideoMessageEventContent::plain(
1770 "Alt text".to_string(),
1771 "mxc://matrix.org/jDErsDugkNlfavzLTjJNUKAH".into()
1772 )
1773 .info(Some(Box::new(info)))
1774 )),
1775 "[Attached Video: Alt text (44 kB)]".to_string().into()
1776 );
1777 }
1778}