src/message/mod.rs
1380 lines · 44666 bytes
1//! # Room Messages
2use std::borrow::Cow;
3use std::cmp::{Ord, Ordering, PartialOrd};
4use std::collections::hash_map::DefaultHasher;
5use std::collections::hash_set;
6use std::collections::BTreeMap;
7use std::convert::TryFrom;
8use std::hash::{Hash, Hasher};
9use std::ops::{Deref, DerefMut};
10
11use chrono::{DateTime, Local as LocalTz, NaiveDateTime, TimeZone};
12use comrak::{markdown_to_html, ComrakOptions};
13use serde_json::json;
14use unicode_width::UnicodeWidthStr;
15
16use matrix_sdk::ruma::{
17 events::{
18 relation::Thread,
19 room::{
20 encrypted::{
21 OriginalRoomEncryptedEvent,
22 RedactedRoomEncryptedEvent,
23 RoomEncryptedEvent,
24 },
25 message::{
26 FormattedBody,
27 MessageFormat,
28 MessageType,
29 OriginalRoomMessageEvent,
30 RedactedRoomMessageEvent,
31 Relation,
32 RoomMessageEvent,
33 RoomMessageEventContent,
34 TextMessageEventContent,
35 },
36 redaction::SyncRoomRedactionEvent,
37 },
38 RedactContent,
39 RedactedUnsigned,
40 },
41 EventId,
42 MilliSecondsSinceUnixEpoch,
43 OwnedEventId,
44 OwnedUserId,
45 RoomVersionId,
46 UInt,
47};
48
49use ratatui::{
50 style::{Modifier as StyleModifier, Style},
51 symbols::line::THICK_VERTICAL,
52 text::{Line, Span, Text},
53};
54
55use modalkit::editing::cursor::Cursor;
56use modalkit::prelude::*;
57use ratatui_image::protocol::Protocol;
58
59use crate::config::ImagePreviewSize;
60use crate::{
61 base::RoomInfo,
62 config::ApplicationSettings,
63 message::html::{parse_matrix_html, StyleTree},
64 util::{replace_emojis_in_str, space, space_span, take_width, wrapped_text},
65};
66
67mod html;
68mod printer;
69
70pub type MessageKey = (MessageTimeStamp, OwnedEventId);
71
72#[derive(Default)]
73pub struct Messages(BTreeMap<MessageKey, Message>);
74
75impl Deref for Messages {
76 type Target = BTreeMap<MessageKey, Message>;
77
78 fn deref(&self) -> &Self::Target {
79 &self.0
80 }
81}
82
83impl DerefMut for Messages {
84 fn deref_mut(&mut self) -> &mut Self::Target {
85 &mut self.0
86 }
87}
88
89impl Messages {
90 pub fn insert_message(&mut self, key: MessageKey, msg: impl Into<Message>) {
91 let event_id = key.1.clone();
92 let msg = msg.into();
93
94 self.0.insert(key, msg);
95
96 // Remove any echo.
97 let key = (MessageTimeStamp::LocalEcho, event_id);
98 let _ = self.0.remove(&key);
99 }
100}
101
102const fn span_static(s: &'static str) -> Span<'static> {
103 Span {
104 content: Cow::Borrowed(s),
105 style: Style {
106 fg: None,
107 bg: None,
108 add_modifier: StyleModifier::empty(),
109 sub_modifier: StyleModifier::empty(),
110 underline_color: None,
111 },
112 }
113}
114
115const BOLD_STYLE: Style = Style {
116 fg: None,
117 bg: None,
118 add_modifier: StyleModifier::BOLD,
119 sub_modifier: StyleModifier::empty(),
120 underline_color: None,
121};
122
123const TIME_GUTTER: usize = 12;
124const READ_GUTTER: usize = 5;
125const MIN_MSG_LEN: usize = 30;
126
127const TIME_GUTTER_EMPTY: &str = " ";
128const TIME_GUTTER_EMPTY_SPAN: Span<'static> = span_static(TIME_GUTTER_EMPTY);
129
130fn text_to_message_content(input: String) -> TextMessageEventContent {
131 let mut options = ComrakOptions::default();
132 options.extension.autolink = true;
133 options.extension.shortcodes = true;
134 options.extension.strikethrough = true;
135 options.render.hardbreaks = true;
136 let html = markdown_to_html(input.as_str(), &options);
137
138 TextMessageEventContent::html(input, html)
139}
140
141pub fn text_to_message(input: String) -> RoomMessageEventContent {
142 let msg = MessageType::Text(text_to_message_content(input));
143 RoomMessageEventContent::new(msg)
144}
145
146/// Before the image is loaded, already display a placeholder frame of the image size.
147fn placeholder_frame(
148 text: Option<&str>,
149 outer_width: usize,
150 image_preview_size: &ImagePreviewSize,
151) -> Option<String> {
152 let ImagePreviewSize { width, height } = image_preview_size;
153 if outer_width < *width || (*width < 2 || *height < 2) {
154 return None;
155 }
156 let mut placeholder = "\u{230c}".to_string();
157 placeholder.push_str(&" ".repeat(width - 2));
158 placeholder.push_str("\u{230d}\n");
159 if *height > 2 {
160 if let Some(text) = text {
161 if text.width() <= width - 2 {
162 placeholder.push(' ');
163 placeholder.push_str(text);
164 }
165 }
166 }
167
168 placeholder.push_str(&"\n".repeat(height - 2));
169 placeholder.push('\u{230e}');
170 placeholder.push_str(&" ".repeat(width - 2));
171 placeholder.push_str("\u{230f}\n");
172 Some(placeholder)
173}
174
175#[inline]
176fn millis_to_datetime(ms: UInt) -> DateTime<LocalTz> {
177 let time = i64::from(ms) / 1000;
178 let time = NaiveDateTime::from_timestamp_opt(time, 0).unwrap_or_default();
179
180 LocalTz.from_utc_datetime(&time)
181}
182
183#[derive(thiserror::Error, Debug)]
184pub enum TimeStampIntError {
185 #[error("Integer conversion error: {0}")]
186 IntError(#[from] std::num::TryFromIntError),
187
188 #[error("UInt conversion error: {0}")]
189 UIntError(<UInt as TryFrom<u64>>::Error),
190}
191
192#[derive(Clone, Copy, Debug, Eq, PartialEq)]
193pub enum MessageTimeStamp {
194 OriginServer(UInt),
195 LocalEcho,
196}
197
198impl MessageTimeStamp {
199 fn as_datetime(&self) -> DateTime<LocalTz> {
200 match self {
201 MessageTimeStamp::OriginServer(ms) => millis_to_datetime(*ms),
202 MessageTimeStamp::LocalEcho => LocalTz::now(),
203 }
204 }
205
206 fn same_day(&self, other: &Self) -> bool {
207 let dt1 = self.as_datetime();
208 let dt2 = other.as_datetime();
209
210 dt1.date_naive() == dt2.date_naive()
211 }
212
213 fn show_date(&self) -> Option<Span> {
214 let time = self.as_datetime().format("%A, %B %d %Y").to_string();
215
216 Span::styled(time, BOLD_STYLE).into()
217 }
218
219 fn show_time(&self) -> Option<Span> {
220 match self {
221 MessageTimeStamp::OriginServer(ms) => {
222 let time = millis_to_datetime(*ms).format("%T");
223 let time = format!(" [{time}]");
224
225 Span::raw(time).into()
226 },
227 MessageTimeStamp::LocalEcho => None,
228 }
229 }
230
231 fn is_local_echo(&self) -> bool {
232 matches!(self, MessageTimeStamp::LocalEcho)
233 }
234
235 pub fn as_millis(&self) -> Option<MilliSecondsSinceUnixEpoch> {
236 match self {
237 MessageTimeStamp::OriginServer(ms) => MilliSecondsSinceUnixEpoch(*ms).into(),
238 MessageTimeStamp::LocalEcho => None,
239 }
240 }
241}
242
243impl Ord for MessageTimeStamp {
244 fn cmp(&self, other: &Self) -> Ordering {
245 match (self, other) {
246 (MessageTimeStamp::OriginServer(_), MessageTimeStamp::LocalEcho) => Ordering::Less,
247 (MessageTimeStamp::OriginServer(a), MessageTimeStamp::OriginServer(b)) => a.cmp(b),
248 (MessageTimeStamp::LocalEcho, MessageTimeStamp::OriginServer(_)) => Ordering::Greater,
249 (MessageTimeStamp::LocalEcho, MessageTimeStamp::LocalEcho) => Ordering::Equal,
250 }
251 }
252}
253
254impl PartialOrd for MessageTimeStamp {
255 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
256 Some(self.cmp(other))
257 }
258}
259
260impl From<UInt> for MessageTimeStamp {
261 fn from(millis: UInt) -> Self {
262 MessageTimeStamp::OriginServer(millis)
263 }
264}
265
266impl From<MilliSecondsSinceUnixEpoch> for MessageTimeStamp {
267 fn from(millis: MilliSecondsSinceUnixEpoch) -> Self {
268 MessageTimeStamp::OriginServer(millis.0)
269 }
270}
271
272impl TryFrom<&MessageTimeStamp> for usize {
273 type Error = TimeStampIntError;
274
275 fn try_from(ts: &MessageTimeStamp) -> Result<Self, Self::Error> {
276 let n = match ts {
277 MessageTimeStamp::LocalEcho => 0,
278 MessageTimeStamp::OriginServer(u) => usize::try_from(u64::from(*u))?,
279 };
280
281 Ok(n)
282 }
283}
284
285impl TryFrom<usize> for MessageTimeStamp {
286 type Error = TimeStampIntError;
287
288 fn try_from(u: usize) -> Result<Self, Self::Error> {
289 if u == 0 {
290 Ok(MessageTimeStamp::LocalEcho)
291 } else {
292 let n = u64::try_from(u)?;
293 let n = UInt::try_from(n).map_err(TimeStampIntError::UIntError)?;
294
295 Ok(MessageTimeStamp::from(n))
296 }
297 }
298}
299
300#[derive(Clone, Debug, Default, Eq, PartialEq)]
301pub struct MessageCursor {
302 /// When timestamp is None, the corner is determined by moving backwards from
303 /// the most recently received message.
304 pub timestamp: Option<MessageKey>,
305
306 /// A row within the [Text] representation of a [Message].
307 pub text_row: usize,
308}
309
310impl MessageCursor {
311 pub fn new(timestamp: MessageKey, text_row: usize) -> Self {
312 MessageCursor { timestamp: Some(timestamp), text_row }
313 }
314
315 /// Get a cursor that refers to the most recent message.
316 pub fn latest() -> Self {
317 MessageCursor::default()
318 }
319
320 pub fn to_key<'a>(&'a self, thread: &'a Messages) -> Option<&'a MessageKey> {
321 if let Some(ref key) = self.timestamp {
322 Some(key)
323 } else {
324 Some(thread.last_key_value()?.0)
325 }
326 }
327
328 pub fn from_cursor(cursor: &Cursor, thread: &Messages) -> Option<Self> {
329 let ev_hash = u64::try_from(cursor.get_x()).ok()?;
330 let ev_term = OwnedEventId::try_from("$").ok()?;
331
332 let ts_start = MessageTimeStamp::try_from(cursor.get_y()).ok()?;
333 let start = (ts_start, ev_term);
334
335 for ((ts, event_id), _) in thread.range(&start..) {
336 let mut hasher = DefaultHasher::new();
337 event_id.hash(&mut hasher);
338
339 if hasher.finish() == ev_hash {
340 return Self::from((*ts, event_id.clone())).into();
341 }
342
343 if ts > &ts_start {
344 break;
345 }
346 }
347
348 // If we can't find the cursor, then go to the nearest timestamp.
349 thread
350 .range(start..)
351 .next()
352 .map(|((ts, ev), _)| Self::from((*ts, ev.clone())))
353 }
354
355 pub fn to_cursor(&self, thread: &Messages) -> Option<Cursor> {
356 let (ts, event_id) = self.to_key(thread)?;
357
358 let y: usize = usize::try_from(ts).ok()?;
359
360 let mut hasher = DefaultHasher::new();
361 event_id.hash(&mut hasher);
362 let x = usize::try_from(hasher.finish()).ok()?;
363
364 Cursor::new(y, x).into()
365 }
366}
367
368impl From<Option<MessageKey>> for MessageCursor {
369 fn from(key: Option<MessageKey>) -> Self {
370 MessageCursor { timestamp: key, text_row: 0 }
371 }
372}
373
374impl From<MessageKey> for MessageCursor {
375 fn from(key: MessageKey) -> Self {
376 MessageCursor { timestamp: Some(key), text_row: 0 }
377 }
378}
379
380impl Ord for MessageCursor {
381 fn cmp(&self, other: &Self) -> Ordering {
382 match (&self.timestamp, &other.timestamp) {
383 (None, None) => self.text_row.cmp(&other.text_row),
384 (None, Some(_)) => Ordering::Greater,
385 (Some(_), None) => Ordering::Less,
386 (Some(st), Some(ot)) => {
387 let pcmp = st.cmp(ot);
388 let tcmp = self.text_row.cmp(&other.text_row);
389
390 pcmp.then(tcmp)
391 },
392 }
393 }
394}
395
396impl PartialOrd for MessageCursor {
397 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
398 Some(self.cmp(other))
399 }
400}
401
402fn redaction_reason(ev: &SyncRoomRedactionEvent) -> Option<&str> {
403 let SyncRoomRedactionEvent::Original(ev) = ev else {
404 return None;
405 };
406
407 return ev.content.reason.as_deref();
408}
409
410fn redaction_unsigned(ev: SyncRoomRedactionEvent) -> RedactedUnsigned {
411 let reason = redaction_reason(&ev);
412 let redacted_because = json!({
413 "content": {
414 "reason": reason
415 },
416 "event_id": ev.event_id(),
417 "sender": ev.sender(),
418 "origin_server_ts": ev.origin_server_ts(),
419 "unsigned": {},
420 });
421 RedactedUnsigned::new(serde_json::from_value(redacted_because).unwrap())
422}
423
424#[derive(Clone)]
425pub enum MessageEvent {
426 EncryptedOriginal(Box<OriginalRoomEncryptedEvent>),
427 EncryptedRedacted(Box<RedactedRoomEncryptedEvent>),
428 Original(Box<OriginalRoomMessageEvent>),
429 Redacted(Box<RedactedRoomMessageEvent>),
430 Local(OwnedEventId, Box<RoomMessageEventContent>),
431}
432
433impl MessageEvent {
434 pub fn event_id(&self) -> &EventId {
435 match self {
436 MessageEvent::EncryptedOriginal(ev) => ev.event_id.as_ref(),
437 MessageEvent::EncryptedRedacted(ev) => ev.event_id.as_ref(),
438 MessageEvent::Original(ev) => ev.event_id.as_ref(),
439 MessageEvent::Redacted(ev) => ev.event_id.as_ref(),
440 MessageEvent::Local(event_id, _) => event_id.as_ref(),
441 }
442 }
443
444 pub fn content(&self) -> Option<&RoomMessageEventContent> {
445 match self {
446 MessageEvent::EncryptedOriginal(_) => None,
447 MessageEvent::Original(ev) => Some(&ev.content),
448 MessageEvent::EncryptedRedacted(_) => None,
449 MessageEvent::Redacted(_) => None,
450 MessageEvent::Local(_, content) => Some(content),
451 }
452 }
453
454 pub fn is_emote(&self) -> bool {
455 matches!(
456 self.content(),
457 Some(RoomMessageEventContent { msgtype: MessageType::Emote(_), .. })
458 )
459 }
460
461 pub fn body(&self) -> Cow<'_, str> {
462 match self {
463 MessageEvent::EncryptedOriginal(_) => "[Unable to decrypt message]".into(),
464 MessageEvent::Original(ev) => body_cow_content(&ev.content),
465 MessageEvent::EncryptedRedacted(ev) => body_cow_reason(&ev.unsigned),
466 MessageEvent::Redacted(ev) => body_cow_reason(&ev.unsigned),
467 MessageEvent::Local(_, content) => body_cow_content(content),
468 }
469 }
470
471 pub fn html(&self) -> Option<StyleTree> {
472 let content = match self {
473 MessageEvent::EncryptedOriginal(_) => return None,
474 MessageEvent::EncryptedRedacted(_) => return None,
475 MessageEvent::Original(ev) => &ev.content,
476 MessageEvent::Redacted(_) => return None,
477 MessageEvent::Local(_, content) => content,
478 };
479
480 if let MessageType::Text(content) = &content.msgtype {
481 if let Some(FormattedBody { format: MessageFormat::Html, body }) = &content.formatted {
482 Some(parse_matrix_html(body.as_str()))
483 } else {
484 None
485 }
486 } else {
487 None
488 }
489 }
490
491 fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
492 match self {
493 MessageEvent::EncryptedOriginal(_) => return,
494 MessageEvent::EncryptedRedacted(_) => return,
495 MessageEvent::Redacted(_) => return,
496 MessageEvent::Local(_, _) => return,
497 MessageEvent::Original(ev) => {
498 let redacted = RedactedRoomMessageEvent {
499 content: ev.content.clone().redact(version),
500 event_id: ev.event_id.clone(),
501 sender: ev.sender.clone(),
502 origin_server_ts: ev.origin_server_ts,
503 room_id: ev.room_id.clone(),
504 unsigned: redaction_unsigned(redaction),
505 };
506 *self = MessageEvent::Redacted(Box::new(redacted));
507 },
508 }
509 }
510}
511
512fn body_cow_content(content: &RoomMessageEventContent) -> Cow<'_, str> {
513 let s = match &content.msgtype {
514 MessageType::Text(content) => content.body.as_str(),
515 MessageType::VerificationRequest(_) => "[Verification Request]",
516 MessageType::Emote(content) => content.body.as_ref(),
517 MessageType::Notice(content) => content.body.as_str(),
518 MessageType::ServerNotice(content) => content.body.as_str(),
519
520 MessageType::Audio(content) => {
521 return Cow::Owned(format!("[Attached Audio: {}]", content.body));
522 },
523 MessageType::File(content) => {
524 return Cow::Owned(format!("[Attached File: {}]", content.body));
525 },
526 MessageType::Image(content) => {
527 return Cow::Owned(format!("[Attached Image: {}]", content.body));
528 },
529 MessageType::Video(content) => {
530 return Cow::Owned(format!("[Attached Video: {}]", content.body));
531 },
532 _ => {
533 return Cow::Owned(format!("[Unknown message type: {:?}]", content.msgtype()));
534 },
535 };
536
537 Cow::Borrowed(s)
538}
539
540fn body_cow_reason(unsigned: &RedactedUnsigned) -> Cow<'_, str> {
541 let reason = unsigned.redacted_because.content.reason.as_ref();
542
543 if let Some(r) = reason {
544 Cow::Owned(format!("[Redacted: {r:?}]"))
545 } else {
546 Cow::Borrowed("[Redacted]")
547 }
548}
549
550enum MessageColumns {
551 /// Four columns: sender, message, timestamp, read receipts.
552 Four,
553
554 /// Three columns: sender, message, timestamp.
555 Three,
556
557 /// Two columns: sender, message.
558 Two,
559
560 /// One column: message with sender on line before the message.
561 One,
562}
563
564impl MessageColumns {
565 fn user_gutter_width(&self, settings: &ApplicationSettings) -> u16 {
566 if let MessageColumns::One = self {
567 0
568 } else {
569 settings.tunables.user_gutter_width as u16
570 }
571 }
572}
573
574struct MessageFormatter<'a> {
575 settings: &'a ApplicationSettings,
576
577 /// How many columns to print.
578 cols: MessageColumns,
579
580 /// The full, original width.
581 orig: usize,
582
583 /// The width that the message contents need to fill.
584 fill: usize,
585
586 /// The formatted Span for the message sender.
587 user: Option<Span<'a>>,
588
589 /// The time the message was sent.
590 time: Option<Span<'a>>,
591
592 /// The date the message was sent.
593 date: Option<Span<'a>>,
594
595 /// Iterator over the users who have read up to this message.
596 read: Option<hash_set::Iter<'a, OwnedUserId>>,
597}
598
599impl<'a> MessageFormatter<'a> {
600 fn width(&self) -> usize {
601 self.fill
602 }
603
604 #[inline]
605 fn push_spans(&mut self, prev_line: Line<'a>, style: Style, text: &mut Text<'a>) {
606 if let Some(date) = self.date.take() {
607 let len = date.content.as_ref().len();
608 let padding = self.orig.saturating_sub(len);
609 let leading = space_span(padding / 2, Style::default());
610 let trailing = space_span(padding.saturating_sub(padding / 2), Style::default());
611
612 text.lines.push(Line::from(vec![leading, date, trailing]));
613 }
614
615 let user_gutter_empty_span =
616 space_span(self.settings.tunables.user_gutter_width, Style::default());
617
618 match self.cols {
619 MessageColumns::Four => {
620 let settings = self.settings;
621 let user = self.user.take().unwrap_or(user_gutter_empty_span);
622 let time = self.time.take().unwrap_or(TIME_GUTTER_EMPTY_SPAN);
623
624 let mut line = vec![user];
625 line.extend(prev_line.spans);
626 line.push(time);
627
628 // Show read receipts.
629 let user_char =
630 |user: &'a OwnedUserId| -> Span<'a> { settings.get_user_char_span(user) };
631 let mut read = self.read.iter_mut().flatten();
632
633 let a = read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
634 let b = read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
635 let c = read.next().map(user_char).unwrap_or_else(|| Span::raw(" "));
636
637 line.push(Span::raw(" "));
638 line.push(c);
639 line.push(b);
640 line.push(a);
641 line.push(Span::raw(" "));
642
643 text.lines.push(Line::from(line))
644 },
645 MessageColumns::Three => {
646 let user = self.user.take().unwrap_or(user_gutter_empty_span);
647 let time = self.time.take().unwrap_or_else(|| Span::from(""));
648
649 let mut line = vec![user];
650 line.extend(prev_line.spans);
651 line.push(time);
652
653 text.lines.push(Line::from(line))
654 },
655 MessageColumns::Two => {
656 let user = self.user.take().unwrap_or(user_gutter_empty_span);
657 let mut line = vec![user];
658 line.extend(prev_line.spans);
659
660 text.lines.push(Line::from(line));
661 },
662 MessageColumns::One => {
663 if let Some(user) = self.user.take() {
664 text.lines.push(Line::from(vec![user]));
665 }
666
667 let leading = space_span(2, style);
668 let mut line = vec![leading];
669 line.extend(prev_line.spans);
670
671 text.lines.push(Line::from(line));
672 },
673 }
674 }
675
676 fn push_text(&mut self, append: Text<'a>, style: Style, text: &mut Text<'a>) {
677 for line in append.lines.into_iter() {
678 self.push_spans(line, style, text);
679 }
680 }
681
682 fn push_in_reply(
683 &mut self,
684 msg: &'a Message,
685 style: Style,
686 text: &mut Text<'a>,
687 info: &'a RoomInfo,
688 ) {
689 let width = self.width();
690 let w = width.saturating_sub(2);
691 let shortcodes = self.settings.tunables.message_shortcode_display;
692 let (mut replied, _) = msg.show_msg(w, style, true, shortcodes);
693 let mut sender = msg.sender_span(info, self.settings);
694 let sender_width = UnicodeWidthStr::width(sender.content.as_ref());
695 let trailing = w.saturating_sub(sender_width + 1);
696
697 sender.style = sender.style.patch(style);
698
699 self.push_spans(
700 Line::from(vec![
701 Span::styled(" ", style),
702 Span::styled(THICK_VERTICAL, style),
703 sender,
704 Span::styled(":", style),
705 space_span(trailing, style),
706 ]),
707 style,
708 text,
709 );
710
711 for line in replied.lines.iter_mut() {
712 line.spans.insert(0, Span::styled(THICK_VERTICAL, style));
713 line.spans.insert(0, Span::styled(" ", style));
714 }
715
716 self.push_text(replied, style, text);
717 }
718
719 fn push_reactions(&mut self, counts: Vec<(&'a str, usize)>, style: Style, text: &mut Text<'a>) {
720 let mut emojis = printer::TextPrinter::new(self.width(), style, false, false);
721 let mut reactions = 0;
722
723 for (key, count) in counts {
724 if reactions != 0 {
725 emojis.push_str(" ", style);
726 }
727
728 let name = if self.settings.tunables.reaction_shortcode_display {
729 if let Some(emoji) = emojis::get(key) {
730 if let Some(short) = emoji.shortcode() {
731 short
732 } else {
733 // No ASCII shortcode name to show.
734 continue;
735 }
736 } else if key.chars().all(|c| c.is_ascii_alphanumeric()) {
737 key
738 } else {
739 // Not an Emoji or a printable ASCII string.
740 continue;
741 }
742 } else {
743 key
744 };
745
746 emojis.push_str("[", style);
747 emojis.push_str(name, style);
748 emojis.push_str(" ", style);
749 emojis.push_span_nobreak(Span::styled(count.to_string(), style));
750 emojis.push_str("]", style);
751
752 reactions += 1;
753 }
754
755 if reactions > 0 {
756 self.push_text(emojis.finish(), style, text);
757 }
758 }
759
760 fn push_thread_reply_count(&mut self, len: usize, text: &mut Text<'a>) {
761 if len == 0 {
762 return;
763 }
764
765 // If we have threaded replies to this message, show how many.
766 let plural = len != 1;
767 let style = Style::default();
768 let mut threaded =
769 printer::TextPrinter::new(self.width(), style, false, false).literal(true);
770 let len = Span::styled(len.to_string(), style.add_modifier(StyleModifier::BOLD));
771 threaded.push_str(" \u{2937} ", style);
772 threaded.push_span_nobreak(len);
773 if plural {
774 threaded.push_str(" replies in thread", style);
775 } else {
776 threaded.push_str(" reply in thread", style);
777 }
778
779 self.push_text(threaded.finish(), style, text);
780 }
781}
782
783pub enum ImageStatus {
784 None,
785 Downloading(ImagePreviewSize),
786 Loaded(Box<dyn Protocol>),
787 Error(String),
788}
789
790pub struct Message {
791 pub event: MessageEvent,
792 pub sender: OwnedUserId,
793 pub timestamp: MessageTimeStamp,
794 pub downloaded: bool,
795 pub html: Option<StyleTree>,
796 pub image_preview: ImageStatus,
797}
798
799impl Message {
800 pub fn new(event: MessageEvent, sender: OwnedUserId, timestamp: MessageTimeStamp) -> Self {
801 let html = event.html();
802 let downloaded = false;
803
804 Message {
805 event,
806 sender,
807 timestamp,
808 downloaded,
809 html,
810 image_preview: ImageStatus::None,
811 }
812 }
813
814 pub fn reply_to(&self) -> Option<OwnedEventId> {
815 let content = match &self.event {
816 MessageEvent::EncryptedOriginal(_) => return None,
817 MessageEvent::EncryptedRedacted(_) => return None,
818 MessageEvent::Local(_, content) => content,
819 MessageEvent::Original(ev) => &ev.content,
820 MessageEvent::Redacted(_) => return None,
821 };
822
823 match &content.relates_to {
824 Some(Relation::Reply { in_reply_to }) => Some(in_reply_to.event_id.clone()),
825 Some(Relation::Thread(Thread {
826 in_reply_to: Some(in_reply_to),
827 is_falling_back: false,
828 ..
829 })) => Some(in_reply_to.event_id.clone()),
830 Some(_) | None => None,
831 }
832 }
833
834 fn thread_root(&self) -> Option<OwnedEventId> {
835 let content = match &self.event {
836 MessageEvent::EncryptedOriginal(_) => return None,
837 MessageEvent::EncryptedRedacted(_) => return None,
838 MessageEvent::Local(_, content) => content,
839 MessageEvent::Original(ev) => &ev.content,
840 MessageEvent::Redacted(_) => return None,
841 };
842
843 match &content.relates_to {
844 Some(Relation::Thread(Thread {
845 event_id,
846 in_reply_to: Some(in_reply_to),
847 is_falling_back: true,
848 ..
849 })) if event_id == &in_reply_to.event_id => Some(event_id.clone()),
850 Some(_) | None => None,
851 }
852 }
853
854 fn get_render_style(&self, selected: bool, settings: &ApplicationSettings) -> Style {
855 let mut style = Style::default();
856
857 if selected {
858 style = style.add_modifier(StyleModifier::REVERSED)
859 }
860
861 if self.timestamp.is_local_echo() {
862 style = style.add_modifier(StyleModifier::ITALIC);
863 }
864
865 if settings.tunables.message_user_color {
866 let color = crate::config::user_color(self.sender.as_str());
867 style = style.fg(color);
868 }
869
870 return style;
871 }
872
873 fn get_render_format<'a>(
874 &'a self,
875 prev: Option<&Message>,
876 width: usize,
877 info: &'a RoomInfo,
878 settings: &'a ApplicationSettings,
879 ) -> MessageFormatter<'a> {
880 let orig = width;
881 let date = match &prev {
882 Some(prev) if prev.timestamp.same_day(&self.timestamp) => None,
883 _ => self.timestamp.show_date(),
884 };
885 let user_gutter = settings.tunables.user_gutter_width;
886
887 if user_gutter + TIME_GUTTER + READ_GUTTER + MIN_MSG_LEN <= width &&
888 settings.tunables.read_receipt_display
889 {
890 let cols = MessageColumns::Four;
891 let fill = width - user_gutter - TIME_GUTTER - READ_GUTTER;
892 let user = self.show_sender(prev, true, info, settings);
893 let time = self.timestamp.show_time();
894 let read = info.event_receipts.get(self.event.event_id()).map(|read| read.iter());
895
896 MessageFormatter { settings, cols, orig, fill, user, date, time, read }
897 } else if user_gutter + TIME_GUTTER + MIN_MSG_LEN <= width {
898 let cols = MessageColumns::Three;
899 let fill = width - user_gutter - TIME_GUTTER;
900 let user = self.show_sender(prev, true, info, settings);
901 let time = self.timestamp.show_time();
902 let read = None;
903
904 MessageFormatter { settings, cols, orig, fill, user, date, time, read }
905 } else if user_gutter + MIN_MSG_LEN <= width {
906 let cols = MessageColumns::Two;
907 let fill = width - user_gutter;
908 let user = self.show_sender(prev, true, info, settings);
909 let time = None;
910 let read = None;
911
912 MessageFormatter { settings, cols, orig, fill, user, date, time, read }
913 } else {
914 let cols = MessageColumns::One;
915 let fill = width.saturating_sub(2);
916 let user = self.show_sender(prev, false, info, settings);
917 let time = None;
918 let read = None;
919
920 MessageFormatter { settings, cols, orig, fill, user, date, time, read }
921 }
922 }
923
924 /// Render the message as a [Text] object for the terminal.
925 ///
926 /// This will also get the image preview Protocol with an x/y offset.
927 pub fn show_with_preview<'a>(
928 &'a self,
929 prev: Option<&Message>,
930 selected: bool,
931 vwctx: &ViewportContext<MessageCursor>,
932 info: &'a RoomInfo,
933 settings: &'a ApplicationSettings,
934 ) -> (Text<'a>, Option<(&dyn Protocol, u16, u16)>) {
935 let width = vwctx.get_width();
936
937 let style = self.get_render_style(selected, settings);
938 let mut fmt = self.get_render_format(prev, width, info, settings);
939 let mut text = Text { lines: vec![] };
940 let width = fmt.width();
941
942 // Show the message that this one replied to, if any.
943 let reply = self
944 .reply_to()
945 .or_else(|| self.thread_root())
946 .and_then(|e| info.get_event(&e));
947
948 if let Some(r) = &reply {
949 fmt.push_in_reply(r, style, &mut text, info);
950 }
951
952 // Now show the message contents, and the inlined reply if we couldn't find it above.
953 let (msg, proto) = self.show_msg(
954 width,
955 style,
956 reply.is_some(),
957 settings.tunables.message_shortcode_display,
958 );
959
960 // Given our text so far, determine the image offset.
961 let proto = proto.map(|p| {
962 let y_off = text.lines.len() as u16;
963 let x_off = fmt.cols.user_gutter_width(settings);
964 (p, x_off, y_off)
965 });
966
967 fmt.push_text(msg, style, &mut text);
968
969 if text.lines.is_empty() {
970 // If there was nothing in the body, just show an empty message.
971 fmt.push_spans(space_span(width, style).into(), style, &mut text);
972 }
973
974 if settings.tunables.reaction_display {
975 let reactions = info.get_reactions(self.event.event_id());
976 fmt.push_reactions(reactions, style, &mut text);
977 }
978
979 if let Some(thread) = info.get_thread(Some(self.event.event_id())) {
980 fmt.push_thread_reply_count(thread.len(), &mut text);
981 }
982
983 (text, proto)
984 }
985
986 pub fn show<'a>(
987 &'a self,
988 prev: Option<&Message>,
989 selected: bool,
990 vwctx: &ViewportContext<MessageCursor>,
991 info: &'a RoomInfo,
992 settings: &'a ApplicationSettings,
993 ) -> Text<'a> {
994 self.show_with_preview(prev, selected, vwctx, info, settings).0
995 }
996
997 fn show_msg(
998 &self,
999 width: usize,
1000 style: Style,
1001 hide_reply: bool,
1002 emoji_shortcodes: bool,
1003 ) -> (Text, Option<&dyn Protocol>) {
1004 if let Some(html) = &self.html {
1005 (html.to_text(width, style, hide_reply, emoji_shortcodes), None)
1006 } else {
1007 let mut msg = self.event.body();
1008 if emoji_shortcodes {
1009 msg = Cow::Owned(replace_emojis_in_str(msg.as_ref()));
1010 }
1011
1012 if self.downloaded {
1013 msg.to_mut().push_str(" \u{2705}");
1014 }
1015
1016 let mut proto = None;
1017 let placeholder = match &self.image_preview {
1018 ImageStatus::None => None,
1019 ImageStatus::Downloading(image_preview_size) => {
1020 placeholder_frame(Some("Downloading..."), width, image_preview_size)
1021 },
1022 ImageStatus::Loaded(backend) => {
1023 proto = Some(backend.as_ref());
1024 placeholder_frame(None, width, &backend.rect().into())
1025 },
1026 ImageStatus::Error(err) => Some(format!("[Image error: {err}]\n")),
1027 };
1028
1029 if let Some(placeholder) = placeholder {
1030 msg.to_mut().insert_str(0, &placeholder);
1031 }
1032
1033 (wrapped_text(msg, width, style), proto)
1034 }
1035 }
1036
1037 fn sender_span<'a>(
1038 &'a self,
1039 info: &'a RoomInfo,
1040 settings: &'a ApplicationSettings,
1041 ) -> Span<'a> {
1042 settings.get_user_span(self.sender.as_ref(), info)
1043 }
1044
1045 fn show_sender<'a>(
1046 &'a self,
1047 prev: Option<&Message>,
1048 align_right: bool,
1049 info: &'a RoomInfo,
1050 settings: &'a ApplicationSettings,
1051 ) -> Option<Span<'a>> {
1052 if let Some(prev) = prev {
1053 if self.sender == prev.sender &&
1054 self.timestamp.same_day(&prev.timestamp) &&
1055 !self.event.is_emote()
1056 {
1057 return None;
1058 }
1059 }
1060
1061 let Span { content, style } = self.sender_span(info, settings);
1062 let user_gutter = settings.tunables.user_gutter_width;
1063 let ((truncated, width), _) = take_width(content, user_gutter - 2);
1064 let padding = user_gutter - 2 - width;
1065
1066 let sender = if align_right {
1067 space(padding) + &truncated + " "
1068 } else {
1069 truncated.into_owned() + &space(padding) + " "
1070 };
1071
1072 Span::styled(sender, style).into()
1073 }
1074
1075 pub fn redact(&mut self, redaction: SyncRoomRedactionEvent, version: &RoomVersionId) {
1076 self.event.redact(redaction, version);
1077 self.html = None;
1078 }
1079}
1080
1081impl From<RoomEncryptedEvent> for Message {
1082 fn from(event: RoomEncryptedEvent) -> Self {
1083 let timestamp = event.origin_server_ts().into();
1084 let user_id = event.sender().to_owned();
1085 let content = match event {
1086 RoomEncryptedEvent::Original(ev) => MessageEvent::EncryptedOriginal(ev.into()),
1087 RoomEncryptedEvent::Redacted(ev) => MessageEvent::EncryptedRedacted(ev.into()),
1088 };
1089
1090 Message::new(content, user_id, timestamp)
1091 }
1092}
1093
1094impl From<OriginalRoomMessageEvent> for Message {
1095 fn from(event: OriginalRoomMessageEvent) -> Self {
1096 let timestamp = event.origin_server_ts.into();
1097 let user_id = event.sender.clone();
1098 let content = MessageEvent::Original(event.into());
1099
1100 Message::new(content, user_id, timestamp)
1101 }
1102}
1103
1104impl From<RedactedRoomMessageEvent> for Message {
1105 fn from(event: RedactedRoomMessageEvent) -> Self {
1106 let timestamp = event.origin_server_ts.into();
1107 let user_id = event.sender.clone();
1108 let content = MessageEvent::Redacted(event.into());
1109
1110 Message::new(content, user_id, timestamp)
1111 }
1112}
1113
1114impl From<RoomMessageEvent> for Message {
1115 fn from(event: RoomMessageEvent) -> Self {
1116 match event {
1117 RoomMessageEvent::Original(ev) => ev.into(),
1118 RoomMessageEvent::Redacted(ev) => ev.into(),
1119 }
1120 }
1121}
1122
1123impl ToString for Message {
1124 fn to_string(&self) -> String {
1125 self.event.body().into_owned()
1126 }
1127}
1128
1129#[cfg(test)]
1130pub mod tests {
1131 use super::*;
1132 use crate::tests::*;
1133
1134 #[test]
1135 fn test_mc_cmp() {
1136 let mc1 = MessageCursor::from(MSG1_KEY.clone());
1137 let mc2 = MessageCursor::from(MSG2_KEY.clone());
1138 let mc3 = MessageCursor::from(MSG3_KEY.clone());
1139 let mc4 = MessageCursor::from(MSG4_KEY.clone());
1140 let mc5 = MessageCursor::from(MSG5_KEY.clone());
1141
1142 // Everything is equal to itself.
1143 assert_eq!(mc1.cmp(&mc1), Ordering::Equal);
1144 assert_eq!(mc2.cmp(&mc2), Ordering::Equal);
1145 assert_eq!(mc3.cmp(&mc3), Ordering::Equal);
1146 assert_eq!(mc4.cmp(&mc4), Ordering::Equal);
1147 assert_eq!(mc5.cmp(&mc5), Ordering::Equal);
1148
1149 // Local echo is always greater than an origin server timestamp.
1150 assert_eq!(mc1.cmp(&mc2), Ordering::Greater);
1151 assert_eq!(mc1.cmp(&mc3), Ordering::Greater);
1152 assert_eq!(mc1.cmp(&mc4), Ordering::Greater);
1153 assert_eq!(mc1.cmp(&mc5), Ordering::Greater);
1154
1155 // mc2 is the smallest timestamp.
1156 assert_eq!(mc2.cmp(&mc1), Ordering::Less);
1157 assert_eq!(mc2.cmp(&mc3), Ordering::Less);
1158 assert_eq!(mc2.cmp(&mc4), Ordering::Less);
1159 assert_eq!(mc2.cmp(&mc5), Ordering::Less);
1160
1161 // mc3 should be less than mc4 because of its event ID.
1162 assert_eq!(mc3.cmp(&mc1), Ordering::Less);
1163 assert_eq!(mc3.cmp(&mc2), Ordering::Greater);
1164 assert_eq!(mc3.cmp(&mc4), Ordering::Less);
1165 assert_eq!(mc3.cmp(&mc5), Ordering::Less);
1166
1167 // mc4 should be greater than mc3 because of its event ID.
1168 assert_eq!(mc4.cmp(&mc1), Ordering::Less);
1169 assert_eq!(mc4.cmp(&mc2), Ordering::Greater);
1170 assert_eq!(mc4.cmp(&mc3), Ordering::Greater);
1171 assert_eq!(mc4.cmp(&mc5), Ordering::Less);
1172
1173 // mc5 is the greatest OriginServer timestamp.
1174 assert_eq!(mc5.cmp(&mc1), Ordering::Less);
1175 assert_eq!(mc5.cmp(&mc2), Ordering::Greater);
1176 assert_eq!(mc5.cmp(&mc3), Ordering::Greater);
1177 assert_eq!(mc5.cmp(&mc4), Ordering::Greater);
1178 }
1179
1180 #[test]
1181 fn test_mc_to_key() {
1182 let messages = mock_messages();
1183 let mc1 = MessageCursor::from(MSG1_KEY.clone());
1184 let mc2 = MessageCursor::from(MSG2_KEY.clone());
1185 let mc3 = MessageCursor::from(MSG3_KEY.clone());
1186 let mc4 = MessageCursor::from(MSG4_KEY.clone());
1187 let mc5 = MessageCursor::from(MSG5_KEY.clone());
1188 let mc6 = MessageCursor::latest();
1189
1190 let k1 = mc1.to_key(&messages).unwrap();
1191 let k2 = mc2.to_key(&messages).unwrap();
1192 let k3 = mc3.to_key(&messages).unwrap();
1193 let k4 = mc4.to_key(&messages).unwrap();
1194 let k5 = mc5.to_key(&messages).unwrap();
1195 let k6 = mc6.to_key(&messages).unwrap();
1196
1197 // These should all be equal to their MSGN_KEYs.
1198 assert_eq!(k1, &MSG1_KEY.clone());
1199 assert_eq!(k2, &MSG2_KEY.clone());
1200 assert_eq!(k3, &MSG3_KEY.clone());
1201 assert_eq!(k4, &MSG4_KEY.clone());
1202 assert_eq!(k5, &MSG5_KEY.clone());
1203
1204 // MessageCursor::latest() turns into the largest key (our local echo message).
1205 assert_eq!(k6, &MSG1_KEY.clone());
1206
1207 // MessageCursor::latest() fails to convert for a room w/o messages.
1208 let messages_empty = Messages::default();
1209 assert_eq!(mc6.to_key(&messages_empty), None);
1210 }
1211
1212 #[test]
1213 fn test_mc_to_from_cursor() {
1214 let messages = mock_messages();
1215 let mc1 = MessageCursor::from(MSG1_KEY.clone());
1216 let mc2 = MessageCursor::from(MSG2_KEY.clone());
1217 let mc3 = MessageCursor::from(MSG3_KEY.clone());
1218 let mc4 = MessageCursor::from(MSG4_KEY.clone());
1219 let mc5 = MessageCursor::from(MSG5_KEY.clone());
1220 let mc6 = MessageCursor::latest();
1221
1222 let identity = |mc: &MessageCursor| {
1223 let c = mc.to_cursor(&messages).unwrap();
1224
1225 MessageCursor::from_cursor(&c, &messages).unwrap()
1226 };
1227
1228 // These should all convert to a Cursor and back to the original value.
1229 assert_eq!(identity(&mc1), mc1);
1230 assert_eq!(identity(&mc2), mc2);
1231 assert_eq!(identity(&mc3), mc3);
1232 assert_eq!(identity(&mc4), mc4);
1233 assert_eq!(identity(&mc5), mc5);
1234
1235 // MessageCursor::latest() should point at the most recent message after conversion.
1236 assert_eq!(identity(&mc6), mc1);
1237 }
1238
1239 #[test]
1240 fn test_markdown_autolink() {
1241 let input = "http://example.com\n";
1242 let content = text_to_message_content(input.into());
1243 assert_eq!(content.body, input);
1244 assert_eq!(
1245 content.formatted.unwrap().body,
1246 "<p><a href=\"http://example.com\">http://example.com</a></p>\n"
1247 );
1248
1249 let input = "www.example.com\n";
1250 let content = text_to_message_content(input.into());
1251 assert_eq!(content.body, input);
1252 assert_eq!(
1253 content.formatted.unwrap().body,
1254 "<p><a href=\"http://www.example.com\">www.example.com</a></p>\n"
1255 );
1256
1257 let input = "See docs (they're at https://iamb.chat)\n";
1258 let content = text_to_message_content(input.into());
1259 assert_eq!(content.body, input);
1260 assert_eq!(
1261 content.formatted.unwrap().body,
1262 "<p>See docs (they're at <a href=\"https://iamb.chat\">https://iamb.chat</a>)</p>\n"
1263 );
1264 }
1265
1266 #[test]
1267 fn test_markdown_message() {
1268 let input = "**bold**\n";
1269 let content = text_to_message_content(input.into());
1270 assert_eq!(content.body, input);
1271 assert_eq!(content.formatted.unwrap().body, "<p><strong>bold</strong></p>\n");
1272
1273 let input = "*emphasis*\n";
1274 let content = text_to_message_content(input.into());
1275 assert_eq!(content.body, input);
1276 assert_eq!(content.formatted.unwrap().body, "<p><em>emphasis</em></p>\n");
1277
1278 let input = "`code`\n";
1279 let content = text_to_message_content(input.into());
1280 assert_eq!(content.body, input);
1281 assert_eq!(content.formatted.unwrap().body, "<p><code>code</code></p>\n");
1282
1283 let input = "```rust\nconst A: usize = 1;\n```\n";
1284 let content = text_to_message_content(input.into());
1285 assert_eq!(content.body, input);
1286 assert_eq!(
1287 content.formatted.unwrap().body,
1288 "<pre><code class=\"language-rust\">const A: usize = 1;\n</code></pre>\n"
1289 );
1290
1291 let input = ":heart:\n";
1292 let content = text_to_message_content(input.into());
1293 assert_eq!(content.body, input);
1294 assert_eq!(content.formatted.unwrap().body, "<p>\u{2764}\u{FE0F}</p>\n");
1295
1296 let input = "para 1\n\npara 2\n";
1297 let content = text_to_message_content(input.into());
1298 assert_eq!(content.body, input);
1299 assert_eq!(content.formatted.unwrap().body, "<p>para 1</p>\n<p>para 2</p>\n");
1300
1301 let input = "line 1\nline 2\n";
1302 let content = text_to_message_content(input.into());
1303 assert_eq!(content.body, input);
1304 assert_eq!(content.formatted.unwrap().body, "<p>line 1<br />\nline 2</p>\n");
1305
1306 let input = "# Heading\n## Subheading\n\ntext\n";
1307 let content = text_to_message_content(input.into());
1308 assert_eq!(content.body, input);
1309 assert_eq!(
1310 content.formatted.unwrap().body,
1311 "<h1>Heading</h1>\n<h2>Subheading</h2>\n<p>text</p>\n"
1312 );
1313 }
1314
1315 #[test]
1316 fn test_placeholder_frame() {
1317 fn pretty_frame_test(str: &str) -> Option<String> {
1318 Some(str[1..].to_string())
1319 }
1320
1321 assert_eq!(
1322 placeholder_frame(None, 4, &ImagePreviewSize { width: 4, height: 4 }),
1323 pretty_frame_test(
1324 r#"
1325⌌ ⌍
1326
1327
1328⌎ ⌏
1329"#
1330 )
1331 );
1332
1333 assert_eq!(placeholder_frame(None, 2, &ImagePreviewSize { width: 4, height: 4 }), None);
1334 assert_eq!(placeholder_frame(None, 4, &ImagePreviewSize { width: 1, height: 4 }), None);
1335
1336 assert_eq!(placeholder_frame(None, 4, &ImagePreviewSize { width: 4, height: 1 }), None);
1337
1338 assert_eq!(
1339 placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 4, height: 4 }),
1340 pretty_frame_test(
1341 r#"
1342⌌ ⌍
1343 OK
1344
1345⌎ ⌏
1346"#
1347 )
1348 );
1349 assert_eq!(
1350 placeholder_frame(Some("idontfit"), 4, &ImagePreviewSize { width: 4, height: 4 }),
1351 pretty_frame_test(
1352 r#"
1353⌌ ⌍
1354
1355
1356⌎ ⌏
1357"#
1358 )
1359 );
1360 assert_eq!(
1361 placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 4, height: 2 }),
1362 pretty_frame_test(
1363 r#"
1364⌌ ⌍
1365⌎ ⌏
1366"#
1367 )
1368 );
1369 assert_eq!(
1370 placeholder_frame(Some("OK"), 4, &ImagePreviewSize { width: 2, height: 3 }),
1371 pretty_frame_test(
1372 r#"
1373⌌⌍
1374
1375⌎⌏
1376"#
1377 )
1378 );
1379 }
1380}