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