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