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