src/message/mod.rs
1034 lines · 33978 bytes
1use std::borrow::Cow;
2use std::cmp::{Ord, Ordering, PartialOrd};
3use std::collections::hash_map::DefaultHasher;
4use std::collections::BTreeMap;
5use std::convert::TryFrom;
6use std::hash::{Hash, Hasher};
7use std::slice::Iter;
8
9use chrono::{DateTime, Local as LocalTz, NaiveDateTime, TimeZone};
10use comrak::{markdown_to_html, ComrakOptions};
11use unicode_width::UnicodeWidthStr;
12
13use matrix_sdk::ruma::{
14 events::{
15 room::{
16 encrypted::{
17 OriginalRoomEncryptedEvent,
18 RedactedRoomEncryptedEvent,
19 RoomEncryptedEvent,
20 },
21 message::{
22 FormattedBody,
23 MessageFormat,
24 MessageType,
25 OriginalRoomMessageEvent,
26 RedactedRoomMessageEvent,
27 Relation,
28 RoomMessageEvent,
29 RoomMessageEventContent,
30 TextMessageEventContent,
31 },
32 redaction::SyncRoomRedactionEvent,
33 },
34 AnyMessageLikeEvent,
35 Redact,
36 RedactedUnsigned,
37 },
38 EventId,
39 MilliSecondsSinceUnixEpoch,
40 OwnedEventId,
41 OwnedUserId,
42 RoomVersionId,
43 UInt,
44};
45
46use modalkit::tui::{
47 style::{Modifier as StyleModifier, Style},
48 symbols::line::THICK_VERTICAL,
49 text::{Span, Spans, Text},
50};
51
52use modalkit::editing::{base::ViewportContext, cursor::Cursor};
53
54use crate::{
55 base::{IambResult, RoomInfo},
56 config::ApplicationSettings,
57 message::html::{parse_matrix_html, StyleTree},
58 util::{space_span, wrapped_text},
59};
60
61mod html;
62mod printer;
63
64pub type MessageFetchResult = IambResult<(Option<String>, Vec<AnyMessageLikeEvent>)>;
65pub type MessageKey = (MessageTimeStamp, OwnedEventId);
66pub type Messages = BTreeMap<MessageKey, Message>;
67
68const fn span_static(s: &'static str) -> Span<'static> {
69 Span {
70 content: Cow::Borrowed(s),
71 style: Style {
72 fg: None,
73 bg: None,
74 add_modifier: StyleModifier::empty(),
75 sub_modifier: StyleModifier::empty(),
76 },
77 }
78}
79
80const BOLD_STYLE: Style = Style {
81 fg: None,
82 bg: None,
83 add_modifier: StyleModifier::BOLD,
84 sub_modifier: StyleModifier::empty(),
85};
86
87const USER_GUTTER: usize = 30;
88const TIME_GUTTER: usize = 12;
89const READ_GUTTER: usize = 5;
90const MIN_MSG_LEN: usize = 30;
91
92const USER_GUTTER_EMPTY: &str = " ";
93const USER_GUTTER_EMPTY_SPAN: Span<'static> = span_static(USER_GUTTER_EMPTY);
94
95const TIME_GUTTER_EMPTY: &str = " ";
96const TIME_GUTTER_EMPTY_SPAN: Span<'static> = span_static(TIME_GUTTER_EMPTY);
97
98fn text_to_message_content(input: String) -> TextMessageEventContent {
99 let mut options = ComrakOptions::default();
100 options.render.hardbreaks = true;
101 let html = markdown_to_html(input.as_str(), &options);
102
103 TextMessageEventContent::html(input, html)
104}
105
106pub fn text_to_message(input: String) -> RoomMessageEventContent {
107 let msg = MessageType::Text(text_to_message_content(input));
108 RoomMessageEventContent::new(msg)
109}
110
111#[inline]
112fn millis_to_datetime(ms: UInt) -> DateTime<LocalTz> {
113 let time = i64::from(ms) / 1000;
114 let time = NaiveDateTime::from_timestamp_opt(time, 0).unwrap_or_default();
115
116 LocalTz.from_utc_datetime(&time)
117}
118
119#[derive(thiserror::Error, Debug)]
120pub enum TimeStampIntError {
121 #[error("Integer conversion error: {0}")]
122 IntError(#[from] std::num::TryFromIntError),
123
124 #[error("UInt conversion error: {0}")]
125 UIntError(<UInt as TryFrom<u64>>::Error),
126}
127
128#[derive(Clone, Copy, Debug, Eq, PartialEq)]
129pub enum MessageTimeStamp {
130 OriginServer(UInt),
131 LocalEcho,
132}
133
134impl MessageTimeStamp {
135 fn as_datetime(&self) -> DateTime<LocalTz> {
136 match self {
137 MessageTimeStamp::OriginServer(ms) => millis_to_datetime(*ms),
138 MessageTimeStamp::LocalEcho => LocalTz::now(),
139 }
140 }
141
142 fn same_day(&self, other: &Self) -> bool {
143 let dt1 = self.as_datetime();
144 let dt2 = other.as_datetime();
145
146 dt1.date_naive() == dt2.date_naive()
147 }
148
149 fn show_date(&self) -> Option<Span> {
150 let time = self.as_datetime().format("%A, %B %d %Y").to_string();
151
152 Span::styled(time, BOLD_STYLE).into()
153 }
154
155 fn show_time(&self) -> Option<Span> {
156 match self {
157 MessageTimeStamp::OriginServer(ms) => {
158 let time = millis_to_datetime(*ms).format("%T");
159 let time = format!(" [{time}]");
160
161 Span::raw(time).into()
162 },
163 MessageTimeStamp::LocalEcho => None,
164 }
165 }
166
167 fn is_local_echo(&self) -> bool {
168 matches!(self, MessageTimeStamp::LocalEcho)
169 }
170
171 pub fn as_millis(&self) -> Option<MilliSecondsSinceUnixEpoch> {
172 match self {
173 MessageTimeStamp::OriginServer(ms) => MilliSecondsSinceUnixEpoch(*ms).into(),
174 MessageTimeStamp::LocalEcho => None,
175 }
176 }
177}
178
179impl Ord for MessageTimeStamp {
180 fn cmp(&self, other: &Self) -> Ordering {
181 match (self, other) {
182 (MessageTimeStamp::OriginServer(_), MessageTimeStamp::LocalEcho) => Ordering::Less,
183 (MessageTimeStamp::OriginServer(a), MessageTimeStamp::OriginServer(b)) => a.cmp(b),
184 (MessageTimeStamp::LocalEcho, MessageTimeStamp::OriginServer(_)) => Ordering::Greater,
185 (MessageTimeStamp::LocalEcho, MessageTimeStamp::LocalEcho) => Ordering::Equal,
186 }
187 }
188}
189
190impl PartialOrd for MessageTimeStamp {
191 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
192 self.cmp(other).into()
193 }
194}
195
196impl From<UInt> for MessageTimeStamp {
197 fn from(millis: UInt) -> Self {
198 MessageTimeStamp::OriginServer(millis)
199 }
200}
201
202impl From<MilliSecondsSinceUnixEpoch> for MessageTimeStamp {
203 fn from(millis: MilliSecondsSinceUnixEpoch) -> Self {
204 MessageTimeStamp::OriginServer(millis.0)
205 }
206}
207
208impl TryFrom<&MessageTimeStamp> for usize {
209 type Error = TimeStampIntError;
210
211 fn try_from(ts: &MessageTimeStamp) -> Result<Self, Self::Error> {
212 let n = match ts {
213 MessageTimeStamp::LocalEcho => 0,
214 MessageTimeStamp::OriginServer(u) => usize::try_from(u64::from(*u))?,
215 };
216
217 Ok(n)
218 }
219}
220
221impl TryFrom<usize> for MessageTimeStamp {
222 type Error = TimeStampIntError;
223
224 fn try_from(u: usize) -> Result<Self, Self::Error> {
225 if u == 0 {
226 Ok(MessageTimeStamp::LocalEcho)
227 } else {
228 let n = u64::try_from(u)?;
229 let n = UInt::try_from(n).map_err(TimeStampIntError::UIntError)?;
230
231 Ok(MessageTimeStamp::from(n))
232 }
233 }
234}
235
236#[derive(Clone, Debug, Default, Eq, PartialEq)]
237pub struct MessageCursor {
238 /// When timestamp is None, the corner is determined by moving backwards from
239 /// the most recently received message.
240 pub timestamp: Option<MessageKey>,
241
242 /// A row within the [Text] representation of a [Message].
243 pub text_row: usize,
244}
245
246impl MessageCursor {
247 pub fn new(timestamp: MessageKey, text_row: usize) -> Self {
248 MessageCursor { timestamp: Some(timestamp), text_row }
249 }
250
251 /// Get a cursor that refers to the most recent message.
252 pub fn latest() -> Self {
253 MessageCursor::default()
254 }
255
256 pub fn to_key<'a>(&'a self, info: &'a RoomInfo) -> Option<&'a MessageKey> {
257 if let Some(ref key) = self.timestamp {
258 Some(key)
259 } else {
260 Some(info.messages.last_key_value()?.0)
261 }
262 }
263
264 pub fn from_cursor(cursor: &Cursor, info: &RoomInfo) -> Option<Self> {
265 let ev_hash = u64::try_from(cursor.get_x()).ok()?;
266 let ev_term = OwnedEventId::try_from("$").ok()?;
267
268 let ts_start = MessageTimeStamp::try_from(cursor.get_y()).ok()?;
269 let start = (ts_start, ev_term);
270 let mut mc = None;
271
272 for ((ts, event_id), _) in info.messages.range(start..) {
273 let mut hasher = DefaultHasher::new();
274 event_id.hash(&mut hasher);
275
276 if hasher.finish() == ev_hash {
277 mc = Self::from((*ts, event_id.clone())).into();
278 break;
279 }
280
281 if mc.is_none() {
282 mc = Self::from((*ts, event_id.clone())).into();
283 }
284
285 if ts > &ts_start {
286 break;
287 }
288 }
289
290 return mc;
291 }
292
293 pub fn to_cursor(&self, info: &RoomInfo) -> Option<Cursor> {
294 let (ts, event_id) = self.to_key(info)?;
295
296 let y: usize = usize::try_from(ts).ok()?;
297
298 let mut hasher = DefaultHasher::new();
299 event_id.hash(&mut hasher);
300 let x = usize::try_from(hasher.finish()).ok()?;
301
302 Cursor::new(y, x).into()
303 }
304}
305
306impl From<Option<MessageKey>> for MessageCursor {
307 fn from(key: Option<MessageKey>) -> Self {
308 MessageCursor { timestamp: key, text_row: 0 }
309 }
310}
311
312impl From<MessageKey> for MessageCursor {
313 fn from(key: MessageKey) -> Self {
314 MessageCursor { timestamp: Some(key), text_row: 0 }
315 }
316}
317
318impl Ord for MessageCursor {
319 fn cmp(&self, other: &Self) -> Ordering {
320 match (&self.timestamp, &other.timestamp) {
321 (None, None) => self.text_row.cmp(&other.text_row),
322 (None, Some(_)) => Ordering::Greater,
323 (Some(_), None) => Ordering::Less,
324 (Some(st), Some(ot)) => {
325 let pcmp = st.cmp(ot);
326 let tcmp = self.text_row.cmp(&other.text_row);
327
328 pcmp.then(tcmp)
329 },
330 }
331 }
332}
333
334impl PartialOrd for MessageCursor {
335 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
336 self.cmp(other).into()
337 }
338}
339
340#[derive(Clone)]
341pub enum MessageEvent {
342 EncryptedOriginal(Box<OriginalRoomEncryptedEvent>),
343 EncryptedRedacted(Box<RedactedRoomEncryptedEvent>),
344 Original(Box<OriginalRoomMessageEvent>),
345 Redacted(Box<RedactedRoomMessageEvent>),
346 Local(OwnedEventId, Box<RoomMessageEventContent>),
347}
348
349impl MessageEvent {
350 pub fn event_id(&self) -> &EventId {
351 match self {
352 MessageEvent::EncryptedOriginal(ev) => ev.event_id.as_ref(),
353 MessageEvent::EncryptedRedacted(ev) => ev.event_id.as_ref(),
354 MessageEvent::Original(ev) => ev.event_id.as_ref(),
355 MessageEvent::Redacted(ev) => ev.event_id.as_ref(),
356 MessageEvent::Local(event_id, _) => event_id.as_ref(),
357 }
358 }
359
360 pub fn content(&self) -> Option<&RoomMessageEventContent> {
361 match self {
362 MessageEvent::EncryptedOriginal(_) => None,
363 MessageEvent::Original(ev) => Some(&ev.content),
364 MessageEvent::EncryptedRedacted(_) => None,
365 MessageEvent::Redacted(_) => None,
366 MessageEvent::Local(_, content) => Some(content),
367 }
368 }
369
370 pub fn is_emote(&self) -> bool {
371 matches!(
372 self.content(),
373 Some(RoomMessageEventContent { msgtype: MessageType::Emote(_), .. })
374 )
375 }
376
377 pub fn body(&self) -> Cow<'_, str> {
378 match self {
379 MessageEvent::EncryptedOriginal(_) => "[Unable to decrypt message]".into(),
380 MessageEvent::Original(ev) => body_cow_content(&ev.content),
381 MessageEvent::EncryptedRedacted(ev) => body_cow_reason(&ev.unsigned),
382 MessageEvent::Redacted(ev) => body_cow_reason(&ev.unsigned),
383 MessageEvent::Local(_, content) => body_cow_content(content),
384 }
385 }
386
387 pub fn html(&self) -> Option<StyleTree> {
388 let content = match self {
389 MessageEvent::EncryptedOriginal(_) => return None,
390 MessageEvent::EncryptedRedacted(_) => return None,
391 MessageEvent::Original(ev) => &ev.content,
392 MessageEvent::Redacted(_) => return None,
393 MessageEvent::Local(_, content) => content,
394 };
395
396 if let MessageType::Text(content) = &content.msgtype {
397 if let Some(FormattedBody { format: MessageFormat::Html, body }) = &content.formatted {
398 Some(parse_matrix_html(body.as_str()))
399 } else {
400 None
401 }
402 } else {
403 None
404 }
405 }
406
407 fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
408 match self {
409 MessageEvent::EncryptedOriginal(_) => return,
410 MessageEvent::EncryptedRedacted(_) => return,
411 MessageEvent::Redacted(_) => return,
412 MessageEvent::Local(_, _) => return,
413 MessageEvent::Original(ev) => {
414 let redacted = ev.clone().redact(redaction, version);
415 *self = MessageEvent::Redacted(Box::new(redacted));
416 },
417 }
418 }
419}
420
421fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
422 let s = match &content.msgtype {
423 MessageType::Text(content) => content.body.as_str(),
424 MessageType::VerificationRequest(_) => "[Verification Request]",
425 MessageType::Emote(content) => content.body.as_ref(),
426 MessageType::Notice(content) => content.body.as_str(),
427 MessageType::ServerNotice(content) => content.body.as_str(),
428
429 MessageType::Audio(content) => {
430 return Cow::Owned(format!("[Attached Audio: {}]", content.body));
431 },
432 MessageType::File(content) => {
433 return Cow::Owned(format!("[Attached File: {}]", content.body));
434 },
435 MessageType::Image(content) => {
436 return Cow::Owned(format!("[Attached Image: {}]", content.body));
437 },
438 MessageType::Video(content) => {
439 return Cow::Owned(format!("[Attached Video: {}]", content.body));
440 },
441 _ => {
442 return Cow::Owned(format!("[Unknown message type: {:?}]", content.msgtype()));
443 },
444 };
445
446 Cow::Borrowed(s)
447}
448
449fn body_cow_reason(unsigned: &RedactedUnsigned) -> Cow<'_, str> {
450 let reason = unsigned
451 .redacted_because
452 .as_ref()
453 .and_then(|e| e.as_original())
454 .and_then(|r| r.content.reason.as_ref());
455
456 if let Some(r) = reason {
457 Cow::Owned(format!("[Redacted: {r:?}]"))
458 } else {
459 Cow::Borrowed("[Redacted]")
460 }
461}
462
463enum MessageColumns {
464 /// Four columns: sender, message, timestamp, read receipts.
465 Four,
466
467 /// Three columns: sender, message, timestamp.
468 Three,
469
470 /// Two columns: sender, message.
471 Two,
472
473 /// One column: message with sender on line before the message.
474 One,
475}
476
477struct MessageFormatter<'a> {
478 settings: &'a ApplicationSettings,
479
480 /// How many columns to print.
481 cols: MessageColumns,
482
483 /// The full, original width.
484 orig: usize,
485
486 /// The width that the message contents need to fill.
487 fill: usize,
488
489 /// The formatted Span for the message sender.
490 user: Option<Span<'a>>,
491
492 /// The time the message was sent.
493 time: Option<Span<'a>>,
494
495 /// The date the message was sent.
496 date: Option<Span<'a>>,
497
498 /// Iterator over the users who have read up to this message.
499 read: Iter<'a, OwnedUserId>,
500}
501
502impl<'a> MessageFormatter<'a> {
503 fn width(&self) -> usize {
504 self.fill
505 }
506
507 #[inline]
508 fn push_spans(&mut self, spans: Spans<'a>, style: Style, text: &mut Text<'a>) {
509 if let Some(date) = self.date.take() {
510 let len = date.content.as_ref().len();
511 let padding = self.orig.saturating_sub(len);
512 let leading = space_span(padding / 2, Style::default());
513 let trailing = space_span(padding.saturating_sub(padding / 2), Style::default());
514
515 text.lines.push(Spans(vec![leading, date, trailing]));
516 }
517
518 match self.cols {
519 MessageColumns::Four => {
520 let settings = self.settings;
521 let user = self.user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
522 let time = self.time.take().unwrap_or(TIME_GUTTER_EMPTY_SPAN);
523
524 let mut line = vec![user];
525 line.extend(spans.0);
526 line.push(time);
527
528 // Show read receipts.
529 let user_char =
530 |user: &'a OwnedUserId| -> Span<'a> { settings.get_user_char_span(user) };
531
532 let a = self.read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
533 let b = self.read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
534 let c = self.read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
535
536 line.push(Span::raw(" "));
537 line.push(c);
538 line.push(b);
539 line.push(a);
540 line.push(Span::raw(" "));
541
542 text.lines.push(Spans(line))
543 },
544 MessageColumns::Three => {
545 let user = self.user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
546 let time = self.time.take().unwrap_or_else(|| Span::from(""));
547
548 let mut line = vec![user];
549 line.extend(spans.0);
550 line.push(time);
551
552 text.lines.push(Spans(line))
553 },
554 MessageColumns::Two => {
555 let user = self.user.take().unwrap_or(USER_GUTTER_EMPTY_SPAN);
556 let mut line = vec![user];
557 line.extend(spans.0);
558
559 text.lines.push(Spans(line));
560 },
561 MessageColumns::One => {
562 if let Some(user) = self.user.take() {
563 text.lines.push(Spans(vec![user]));
564 }
565
566 let leading = space_span(2, style);
567 let mut line = vec![leading];
568 line.extend(spans.0);
569
570 text.lines.push(Spans(line));
571 },
572 }
573 }
574
575 fn push_text(&mut self, append: Text<'a>, style: Style, text: &mut Text<'a>) {
576 for line in append.lines.into_iter() {
577 self.push_spans(line, style, text);
578 }
579 }
580}
581
582pub struct Message {
583 pub event: MessageEvent,
584 pub sender: OwnedUserId,
585 pub timestamp: MessageTimeStamp,
586 pub downloaded: bool,
587 pub html: Option<StyleTree>,
588}
589
590impl Message {
591 pub fn new(event: MessageEvent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self {
592 let html = event.html();
593 let downloaded = false;
594
595 Message { event, sender, timestamp, downloaded, html }
596 }
597
598 pub fn reply_to(&self) -> Option<OwnedEventId> {
599 let content = match &self.event {
600 MessageEvent::EncryptedOriginal(_) => return None,
601 MessageEvent::EncryptedRedacted(_) => return None,
602 MessageEvent::Local(_, content) => content,
603 MessageEvent::Original(ev) => &ev.content,
604 MessageEvent::Redacted(_) => return None,
605 };
606
607 if let Some(Relation::Reply { in_reply_to }) = &content.relates_to {
608 Some(in_reply_to.event_id.clone())
609 } else {
610 None
611 }
612 }
613
614 fn get_render_style(&self, selected: bool) -> Style {
615 let mut style = Style::default();
616
617 if selected {
618 style = style.add_modifier(StyleModifier::REVERSED)
619 }
620
621 if self.timestamp.is_local_echo() {
622 style = style.add_modifier(StyleModifier::ITALIC);
623 }
624
625 return style;
626 }
627
628 fn get_render_format<'a>(
629 &'a self,
630 prev: Option<&Message>,
631 width: usize,
632 info: &'a RoomInfo,
633 settings: &'a ApplicationSettings,
634 ) -> MessageFormatter<'a> {
635 let orig = width;
636 let date = match &prev {
637 Some(prev) if prev.timestamp.same_day(&self.timestamp) => None,
638 _ => self.timestamp.show_date(),
639 };
640
641 if USER_GUTTER + TIME_GUTTER + READ_GUTTER + MIN_MSG_LEN <= width &&
642 settings.tunables.read_receipt_display
643 {
644 let cols = MessageColumns::Four;
645 let fill = width - USER_GUTTER - TIME_GUTTER - READ_GUTTER;
646 let user = self.show_sender(prev, true, settings);
647 let time = self.timestamp.show_time();
648 let read = match info.receipts.get(self.event.event_id()) {
649 Some(read) => read.iter(),
650 None => [].iter(),
651 };
652
653 MessageFormatter { settings, cols, orig, fill, user, date, time, read }
654 } else if USER_GUTTER + TIME_GUTTER + MIN_MSG_LEN <= width {
655 let cols = MessageColumns::Three;
656 let fill = width - USER_GUTTER - TIME_GUTTER;
657 let user = self.show_sender(prev, true, settings);
658 let time = self.timestamp.show_time();
659 let read = [].iter();
660
661 MessageFormatter { settings, cols, orig, fill, user, date, time, read }
662 } else if USER_GUTTER + MIN_MSG_LEN <= width {
663 let cols = MessageColumns::Two;
664 let fill = width - USER_GUTTER;
665 let user = self.show_sender(prev, true, settings);
666 let time = None;
667 let read = [].iter();
668
669 MessageFormatter { settings, cols, orig, fill, user, date, time, read }
670 } else {
671 let cols = MessageColumns::One;
672 let fill = width.saturating_sub(2);
673 let user = self.show_sender(prev, false, settings);
674 let time = None;
675 let read = [].iter();
676
677 MessageFormatter { settings, cols, orig, fill, user, date, time, read }
678 }
679 }
680
681 pub fn show<'a>(
682 &'a self,
683 prev: Option<&Message>,
684 selected: bool,
685 vwctx: &ViewportContext<MessageCursor>,
686 info: &'a RoomInfo,
687 settings: &'a ApplicationSettings,
688 ) -> Text<'a> {
689 let width = vwctx.get_width();
690
691 let style = self.get_render_style(selected);
692 let mut fmt = self.get_render_format(prev, width, info, settings);
693 let mut text = Text { lines: vec![] };
694 let width = fmt.width();
695
696 // Show the message that this one replied to, if any.
697 let reply = self.reply_to().and_then(|e| info.get_event(&e));
698
699 if let Some(r) = &reply {
700 let w = width.saturating_sub(2);
701 let mut replied = r.show_msg(w, style, true);
702 let mut sender = r.sender_span(settings);
703 let sender_width = UnicodeWidthStr::width(sender.content.as_ref());
704 let trailing = w.saturating_sub(sender_width + 1);
705
706 sender.style = sender.style.patch(style);
707
708 fmt.push_spans(
709 Spans(vec![
710 Span::styled(" ", style),
711 Span::styled(THICK_VERTICAL, style),
712 sender,
713 Span::styled(":", style),
714 space_span(trailing, style),
715 ]),
716 style,
717 &mut text,
718 );
719
720 for line in replied.lines.iter_mut() {
721 line.0.insert(0, Span::styled(THICK_VERTICAL, style));
722 line.0.insert(0, Span::styled(" ", style));
723 }
724
725 fmt.push_text(replied, style, &mut text);
726 }
727
728 // Now show the message contents, and the inlined reply if we couldn't find it above.
729 let msg = self.show_msg(width, style, reply.is_some());
730 fmt.push_text(msg, style, &mut text);
731
732 if text.lines.is_empty() {
733 // If there was nothing in the body, just show an empty message.
734 fmt.push_spans(space_span(width, style).into(), style, &mut text);
735 }
736
737 if settings.tunables.reaction_display {
738 let mut emojis = printer::TextPrinter::new(width, style, false);
739 let mut reactions = 0;
740
741 for (key, count) in info.get_reactions(self.event.event_id()).into_iter() {
742 if reactions != 0 {
743 emojis.push_str(" ", style);
744 }
745
746 let name = if settings.tunables.reaction_shortcode_display {
747 if let Some(emoji) = emojis::get(key) {
748 if let Some(short) = emoji.shortcode() {
749 short
750 } else {
751 // No ASCII shortcode name to show.
752 continue;
753 }
754 } else if key.chars().all(|c| c.is_ascii_alphanumeric()) {
755 key
756 } else {
757 // Not an Emoji or a printable ASCII string.
758 continue;
759 }
760 } else {
761 key
762 };
763
764 emojis.push_str("[", style);
765 emojis.push_str(name, style);
766 emojis.push_str(" ", style);
767 emojis.push_span_nobreak(Span::styled(count.to_string(), style));
768 emojis.push_str("]", style);
769
770 reactions += 1;
771 }
772
773 if reactions > 0 {
774 fmt.push_text(emojis.finish(), style, &mut text);
775 }
776 }
777
778 return text;
779 }
780
781 pub fn show_msg(&self, width: usize, style: Style, hide_reply: bool) -> Text {
782 if let Some(html) = &self.html {
783 html.to_text(width, style, hide_reply)
784 } else {
785 let mut msg = self.event.body();
786
787 if self.downloaded {
788 msg.to_mut().push_str(" \u{2705}");
789 }
790
791 wrapped_text(msg, width, style)
792 }
793 }
794
795 fn sender_span(&self, settings: &ApplicationSettings) -> Span {
796 settings.get_user_span(self.sender.as_ref())
797 }
798
799 fn show_sender(
800 &self,
801 prev: Option<&Message>,
802 align_right: bool,
803 settings: &ApplicationSettings,
804 ) -> Option<Span> {
805 if let Some(prev) = prev {
806 if self.sender == prev.sender &&
807 self.timestamp.same_day(&prev.timestamp) &&
808 !self.event.is_emote()
809 {
810 return None;
811 }
812 }
813
814 let Span { content, style } = self.sender_span(settings);
815 let stop = content.len().min(28);
816 let s = &content[..stop];
817
818 let sender = if align_right {
819 format!("{: >width$} ", s, width = 28)
820 } else {
821 format!("{: <width$} ", s, width = 28)
822 };
823
824 Span::styled(sender, style).into()
825 }
826
827 pub fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
828 self.event.redact(redaction, version);
829 self.html = None;
830 }
831}
832
833impl From<RoomEncryptedEvent> for Message {
834 fn from(event: RoomEncryptedEvent) -> Self {
835 let timestamp = event.origin_server_ts().into();
836 let user_id = event.sender().to_owned();
837 let content = match event {
838 RoomEncryptedEvent::Original(ev) => MessageEvent::EncryptedOriginal(ev.into()),
839 RoomEncryptedEvent::Redacted(ev) => MessageEvent::EncryptedRedacted(ev.into()),
840 };
841
842 Message::new(content, user_id, timestamp)
843 }
844}
845
846impl From<OriginalRoomMessageEvent> for Message {
847 fn from(event: OriginalRoomMessageEvent) -> Self {
848 let timestamp = event.origin_server_ts.into();
849 let user_id = event.sender.clone();
850 let content = MessageEvent::Original(event.into());
851
852 Message::new(content, user_id, timestamp)
853 }
854}
855
856impl From<RedactedRoomMessageEvent> for Message {
857 fn from(event: RedactedRoomMessageEvent) -> Self {
858 let timestamp = event.origin_server_ts.into();
859 let user_id = event.sender.clone();
860 let content = MessageEvent::Redacted(event.into());
861
862 Message::new(content, user_id, timestamp)
863 }
864}
865
866impl From<RoomMessageEvent> for Message {
867 fn from(event: RoomMessageEvent) -> Self {
868 match event {
869 RoomMessageEvent::Original(ev) => ev.into(),
870 RoomMessageEvent::Redacted(ev) => ev.into(),
871 }
872 }
873}
874
875impl ToString for Message {
876 fn to_string(&self) -> String {
877 self.event.body().into_owned()
878 }
879}
880
881#[cfg(test)]
882pub mod tests {
883 use super::*;
884 use crate::tests::*;
885
886 #[test]
887 fn test_mc_cmp() {
888 let mc1 = MessageCursor::from(MSG1_KEY.clone());
889 let mc2 = MessageCursor::from(MSG2_KEY.clone());
890 let mc3 = MessageCursor::from(MSG3_KEY.clone());
891 let mc4 = MessageCursor::from(MSG4_KEY.clone());
892 let mc5 = MessageCursor::from(MSG5_KEY.clone());
893
894 // Everything is equal to itself.
895 assert_eq!(mc1.cmp(&mc1), Ordering::Equal);
896 assert_eq!(mc2.cmp(&mc2), Ordering::Equal);
897 assert_eq!(mc3.cmp(&mc3), Ordering::Equal);
898 assert_eq!(mc4.cmp(&mc4), Ordering::Equal);
899 assert_eq!(mc5.cmp(&mc5), Ordering::Equal);
900
901 // Local echo is always greater than an origin server timestamp.
902 assert_eq!(mc1.cmp(&mc2), Ordering::Greater);
903 assert_eq!(mc1.cmp(&mc3), Ordering::Greater);
904 assert_eq!(mc1.cmp(&mc4), Ordering::Greater);
905 assert_eq!(mc1.cmp(&mc5), Ordering::Greater);
906
907 // mc2 is the smallest timestamp.
908 assert_eq!(mc2.cmp(&mc1), Ordering::Less);
909 assert_eq!(mc2.cmp(&mc3), Ordering::Less);
910 assert_eq!(mc2.cmp(&mc4), Ordering::Less);
911 assert_eq!(mc2.cmp(&mc5), Ordering::Less);
912
913 // mc3 should be less than mc4 because of its event ID.
914 assert_eq!(mc3.cmp(&mc1), Ordering::Less);
915 assert_eq!(mc3.cmp(&mc2), Ordering::Greater);
916 assert_eq!(mc3.cmp(&mc4), Ordering::Less);
917 assert_eq!(mc3.cmp(&mc5), Ordering::Less);
918
919 // mc4 should be greater than mc3 because of its event ID.
920 assert_eq!(mc4.cmp(&mc1), Ordering::Less);
921 assert_eq!(mc4.cmp(&mc2), Ordering::Greater);
922 assert_eq!(mc4.cmp(&mc3), Ordering::Greater);
923 assert_eq!(mc4.cmp(&mc5), Ordering::Less);
924
925 // mc5 is the greatest OriginServer timestamp.
926 assert_eq!(mc5.cmp(&mc1), Ordering::Less);
927 assert_eq!(mc5.cmp(&mc2), Ordering::Greater);
928 assert_eq!(mc5.cmp(&mc3), Ordering::Greater);
929 assert_eq!(mc5.cmp(&mc4), Ordering::Greater);
930 }
931
932 #[test]
933 fn test_mc_to_key() {
934 let info = mock_room();
935 let mc1 = MessageCursor::from(MSG1_KEY.clone());
936 let mc2 = MessageCursor::from(MSG2_KEY.clone());
937 let mc3 = MessageCursor::from(MSG3_KEY.clone());
938 let mc4 = MessageCursor::from(MSG4_KEY.clone());
939 let mc5 = MessageCursor::from(MSG5_KEY.clone());
940 let mc6 = MessageCursor::latest();
941
942 let k1 = mc1.to_key(&info).unwrap();
943 let k2 = mc2.to_key(&info).unwrap();
944 let k3 = mc3.to_key(&info).unwrap();
945 let k4 = mc4.to_key(&info).unwrap();
946 let k5 = mc5.to_key(&info).unwrap();
947 let k6 = mc6.to_key(&info).unwrap();
948
949 // These should all be equal to their MSGN_KEYs.
950 assert_eq!(k1, &MSG1_KEY.clone());
951 assert_eq!(k2, &MSG2_KEY.clone());
952 assert_eq!(k3, &MSG3_KEY.clone());
953 assert_eq!(k4, &MSG4_KEY.clone());
954 assert_eq!(k5, &MSG5_KEY.clone());
955
956 // MessageCursor::latest() turns into the largest key (our local echo message).
957 assert_eq!(k6, &MSG1_KEY.clone());
958
959 // MessageCursor::latest() fails to convert for a room w/o messages.
960 let info_empty = RoomInfo::default();
961 assert_eq!(mc6.to_key(&info_empty), None);
962 }
963
964 #[test]
965 fn test_mc_to_from_cursor() {
966 let info = mock_room();
967 let mc1 = MessageCursor::from(MSG1_KEY.clone());
968 let mc2 = MessageCursor::from(MSG2_KEY.clone());
969 let mc3 = MessageCursor::from(MSG3_KEY.clone());
970 let mc4 = MessageCursor::from(MSG4_KEY.clone());
971 let mc5 = MessageCursor::from(MSG5_KEY.clone());
972 let mc6 = MessageCursor::latest();
973
974 let identity = |mc: &MessageCursor| {
975 let c = mc.to_cursor(&info).unwrap();
976
977 MessageCursor::from_cursor(&c, &info).unwrap()
978 };
979
980 // These should all convert to a Cursor and back to the original value.
981 assert_eq!(identity(&mc1), mc1);
982 assert_eq!(identity(&mc2), mc2);
983 assert_eq!(identity(&mc3), mc3);
984 assert_eq!(identity(&mc4), mc4);
985 assert_eq!(identity(&mc5), mc5);
986
987 // MessageCursor::latest() should point at the most recent message after conversion.
988 assert_eq!(identity(&mc6), mc1);
989 }
990
991 #[test]
992 fn test_markdown_message() {
993 let input = "**bold**\n";
994 let content = text_to_message_content(input.into());
995 assert_eq!(content.body, input);
996 assert_eq!(content.formatted.unwrap().body, "<p><strong>bold</strong></p>\n");
997
998 let input = "*emphasis*\n";
999 let content = text_to_message_content(input.into());
1000 assert_eq!(content.body, input);
1001 assert_eq!(content.formatted.unwrap().body, "<p><em>emphasis</em></p>\n");
1002
1003 let input = "`code`\n";
1004 let content = text_to_message_content(input.into());
1005 assert_eq!(content.body, input);
1006 assert_eq!(content.formatted.unwrap().body, "<p><code>code</code></p>\n");
1007
1008 let input = "```rust\nconst A: usize = 1;\n```\n";
1009 let content = text_to_message_content(input.into());
1010 assert_eq!(content.body, input);
1011 assert_eq!(
1012 content.formatted.unwrap().body,
1013 "<pre><code class=\"language-rust\">const A: usize = 1;\n</code></pre>\n"
1014 );
1015
1016 let input = "para 1\n\npara 2\n";
1017 let content = text_to_message_content(input.into());
1018 assert_eq!(content.body, input);
1019 assert_eq!(content.formatted.unwrap().body, "<p>para 1</p>\n<p>para 2</p>\n");
1020
1021 let input = "line 1\nline 2\n";
1022 let content = text_to_message_content(input.into());
1023 assert_eq!(content.body, input);
1024 assert_eq!(content.formatted.unwrap().body, "<p>line 1<br />\nline 2</p>\n");
1025
1026 let input = "# Heading\n## Subheading\n\ntext\n";
1027 let content = text_to_message_content(input.into());
1028 assert_eq!(content.body, input);
1029 assert_eq!(
1030 content.formatted.unwrap().body,
1031 "<h1>Heading</h1>\n<h2>Subheading</h2>\n<p>text</p>\n"
1032 );
1033 }
1034}