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