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